pdelay
Plasma delay effect calculator.
sqlite3.c
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.14.1. By combining all the individual C code files into this
4 ** single large file, the entire code can be compiled as a single translation
5 ** unit. This allows many compilers to do optimizations that would not be
6 ** possible if the files were compiled separately. Performance improvements
7 ** of 5% or more are commonly seen when SQLite is compiled as a single
8 ** translation unit.
9 **
10 ** This file is all you need to compile SQLite. To use SQLite in other
11 ** programs, you need this file and the "sqlite3.h" header file that defines
12 ** the programming interface to the SQLite library. (If you do not have
13 ** the "sqlite3.h" header file at hand, you will find a copy embedded within
14 ** the text of this file. Search for "Begin file sqlite3.h" to find the start
15 ** of the embedded sqlite3.h header file.) Additional code files may be needed
16 ** if you want a wrapper to interface SQLite with your choice of programming
17 ** language. The code for the "sqlite3" command-line shell is also in a
18 ** separate file. This file contains only code for the core SQLite library.
19 */
20 #define SQLITE_CORE 1
21 #define SQLITE_AMALGAMATION 1
22 #ifndef SQLITE_PRIVATE
23 # define SQLITE_PRIVATE static
24 #endif
25 /************** Begin file sqliteInt.h ***************************************/
26 /*
27 ** 2001 September 15
28 **
29 ** The author disclaims copyright to this source code. In place of
30 ** a legal notice, here is a blessing:
31 **
32 ** May you do good and not evil.
33 ** May you find forgiveness for yourself and forgive others.
34 ** May you share freely, never taking more than you give.
35 **
36 *************************************************************************
37 ** Internal interface definitions for SQLite.
38 **
39 */
40 #ifndef SQLITEINT_H
41 #define SQLITEINT_H
42 
43 /* Special Comments:
44 **
45 ** Some comments have special meaning to the tools that measure test
46 ** coverage:
47 **
48 ** NO_TEST - The branches on this line are not
49 ** measured by branch coverage. This is
50 ** used on lines of code that actually
51 ** implement parts of coverage testing.
52 **
53 ** OPTIMIZATION-IF-TRUE - This branch is allowed to alway be false
54 ** and the correct answer is still obtained,
55 ** though perhaps more slowly.
56 **
57 ** OPTIMIZATION-IF-FALSE - This branch is allowed to alway be true
58 ** and the correct answer is still obtained,
59 ** though perhaps more slowly.
60 **
61 ** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread
62 ** that would be harmless and undetectable
63 ** if it did occur.
64 **
65 ** In all cases, the special comment must be enclosed in the usual
66 ** slash-asterisk...asterisk-slash comment marks, with no spaces between the
67 ** asterisks and the comment text.
68 */
69 
70 /*
71 ** Make sure the Tcl calling convention macro is defined. This macro is
72 ** only used by test code and Tcl integration code.
73 */
74 #ifndef SQLITE_TCLAPI
75 # define SQLITE_TCLAPI
76 #endif
77 
78 /*
79 ** Make sure that rand_s() is available on Windows systems with MSVC 2005
80 ** or higher.
81 */
82 #if defined(_MSC_VER) && _MSC_VER>=1400
83 # define _CRT_RAND_S
84 #endif
85 
86 /*
87 ** Include the header file used to customize the compiler options for MSVC.
88 ** This should be done first so that it can successfully prevent spurious
89 ** compiler warnings due to subsequent content in this file and other files
90 ** that are included by this file.
91 */
92 /************** Include msvc.h in the middle of sqliteInt.h ******************/
93 /************** Begin file msvc.h ********************************************/
94 /*
95 ** 2015 January 12
96 **
97 ** The author disclaims copyright to this source code. In place of
98 ** a legal notice, here is a blessing:
99 **
100 ** May you do good and not evil.
101 ** May you find forgiveness for yourself and forgive others.
102 ** May you share freely, never taking more than you give.
103 **
104 ******************************************************************************
105 **
106 ** This file contains code that is specific to MSVC.
107 */
108 #ifndef SQLITE_MSVC_H
109 #define SQLITE_MSVC_H
110 
111 #if defined(_MSC_VER)
112 #pragma warning(disable : 4054)
113 #pragma warning(disable : 4055)
114 #pragma warning(disable : 4100)
115 #pragma warning(disable : 4127)
116 #pragma warning(disable : 4130)
117 #pragma warning(disable : 4152)
118 #pragma warning(disable : 4189)
119 #pragma warning(disable : 4206)
120 #pragma warning(disable : 4210)
121 #pragma warning(disable : 4232)
122 #pragma warning(disable : 4244)
123 #pragma warning(disable : 4305)
124 #pragma warning(disable : 4306)
125 #pragma warning(disable : 4702)
126 #pragma warning(disable : 4706)
127 #endif /* defined(_MSC_VER) */
128 
129 #endif /* SQLITE_MSVC_H */
130 
131 /************** End of msvc.h ************************************************/
132 /************** Continuing where we left off in sqliteInt.h ******************/
133 
134 /*
135 ** Special setup for VxWorks
136 */
137 /************** Include vxworks.h in the middle of sqliteInt.h ***************/
138 /************** Begin file vxworks.h *****************************************/
139 /*
140 ** 2015-03-02
141 **
142 ** The author disclaims copyright to this source code. In place of
143 ** a legal notice, here is a blessing:
144 **
145 ** May you do good and not evil.
146 ** May you find forgiveness for yourself and forgive others.
147 ** May you share freely, never taking more than you give.
148 **
149 ******************************************************************************
150 **
151 ** This file contains code that is specific to Wind River's VxWorks
152 */
153 #if defined(__RTP__) || defined(_WRS_KERNEL)
154 /* This is VxWorks. Set up things specially for that OS
155 */
156 #include <vxWorks.h>
157 #include <pthread.h> /* amalgamator: dontcache */
158 #define OS_VXWORKS 1
159 #define SQLITE_OS_OTHER 0
160 #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
161 #define SQLITE_OMIT_LOAD_EXTENSION 1
162 #define SQLITE_ENABLE_LOCKING_STYLE 0
163 #define HAVE_UTIME 1
164 #else
165 /* This is not VxWorks. */
166 #define OS_VXWORKS 0
167 #define HAVE_FCHOWN 1
168 #define HAVE_READLINK 1
169 #define HAVE_LSTAT 1
170 #endif /* defined(_WRS_KERNEL) */
171 
172 /************** End of vxworks.h *********************************************/
173 /************** Continuing where we left off in sqliteInt.h ******************/
174 
175 /*
176 ** These #defines should enable >2GB file support on POSIX if the
177 ** underlying operating system supports it. If the OS lacks
178 ** large file support, or if the OS is windows, these should be no-ops.
179 **
180 ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
181 ** system #includes. Hence, this block of code must be the very first
182 ** code in all source files.
183 **
184 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
185 ** on the compiler command line. This is necessary if you are compiling
186 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
187 ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
188 ** without this option, LFS is enable. But LFS does not exist in the kernel
189 ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
190 ** portability you should omit LFS.
191 **
192 ** The previous paragraph was written in 2005. (This paragraph is written
193 ** on 2008-11-28.) These days, all Linux kernels support large files, so
194 ** you should probably leave LFS enabled. But some embedded platforms might
195 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
196 **
197 ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
198 */
199 #ifndef SQLITE_DISABLE_LFS
200 # define _LARGE_FILE 1
201 # ifndef _FILE_OFFSET_BITS
202 # define _FILE_OFFSET_BITS 64
203 # endif
204 # define _LARGEFILE_SOURCE 1
205 #endif
206 
207 /* What version of GCC is being used. 0 means GCC is not being used */
208 #ifdef __GNUC__
209 # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
210 #else
211 # define GCC_VERSION 0
212 #endif
213 
214 /* Needed for various definitions... */
215 #if defined(__GNUC__) && !defined(_GNU_SOURCE)
216 # define _GNU_SOURCE
217 #endif
218 
219 #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
220 # define _BSD_SOURCE
221 #endif
222 
223 /*
224 ** For MinGW, check to see if we can include the header file containing its
225 ** version information, among other things. Normally, this internal MinGW
226 ** header file would [only] be included automatically by other MinGW header
227 ** files; however, the contained version information is now required by this
228 ** header file to work around binary compatibility issues (see below) and
229 ** this is the only known way to reliably obtain it. This entire #if block
230 ** would be completely unnecessary if there was any other way of detecting
231 ** MinGW via their preprocessor (e.g. if they customized their GCC to define
232 ** some MinGW-specific macros). When compiling for MinGW, either the
233 ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
234 ** defined; otherwise, detection of conditions specific to MinGW will be
235 ** disabled.
236 */
237 #if defined(_HAVE_MINGW_H)
238 # include "mingw.h"
239 #elif defined(_HAVE__MINGW_H)
240 # include "_mingw.h"
241 #endif
242 
243 /*
244 ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
245 ** define is required to maintain binary compatibility with the MSVC runtime
246 ** library in use (e.g. for Windows XP).
247 */
248 #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
249  defined(_WIN32) && !defined(_WIN64) && \
250  defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
251  defined(__MSVCRT__)
252 # define _USE_32BIT_TIME_T
253 #endif
254 
255 /* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
256 ** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
257 ** MinGW.
258 */
259 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
260 /************** Begin file sqlite3.h *****************************************/
261 /*
262 ** 2001 September 15
263 **
264 ** The author disclaims copyright to this source code. In place of
265 ** a legal notice, here is a blessing:
266 **
267 ** May you do good and not evil.
268 ** May you find forgiveness for yourself and forgive others.
269 ** May you share freely, never taking more than you give.
270 **
271 *************************************************************************
272 ** This header file defines the interface that the SQLite library
273 ** presents to client programs. If a C-function, structure, datatype,
274 ** or constant definition does not appear in this file, then it is
275 ** not a published API of SQLite, is subject to change without
276 ** notice, and should not be referenced by programs that use SQLite.
277 **
278 ** Some of the definitions that are in this file are marked as
279 ** "experimental". Experimental interfaces are normally new
280 ** features recently added to SQLite. We do not anticipate changes
281 ** to experimental interfaces but reserve the right to make minor changes
282 ** if experience from use "in the wild" suggest such changes are prudent.
283 **
284 ** The official C-language API documentation for SQLite is derived
285 ** from comments in this file. This file is the authoritative source
286 ** on how SQLite interfaces are supposed to operate.
287 **
288 ** The name of this file under configuration management is "sqlite.h.in".
289 ** The makefile makes some minor changes to this file (such as inserting
290 ** the version number) and changes its name to "sqlite3.h" as
291 ** part of the build process.
292 */
293 #ifndef SQLITE3_H
294 #define SQLITE3_H
295 #include <stdarg.h> /* Needed for the definition of va_list */
296 
297 /*
298 ** Make sure we can call this stuff from C++.
299 */
300 #if 0
301 extern "C" {
302 #endif
303 
304 
305 /*
306 ** Provide the ability to override linkage features of the interface.
307 */
308 #ifndef SQLITE_EXTERN
309 # define SQLITE_EXTERN extern
310 #endif
311 #ifndef SQLITE_API
312 # define SQLITE_API
313 #endif
314 #ifndef SQLITE_CDECL
315 # define SQLITE_CDECL
316 #endif
317 #ifndef SQLITE_APICALL
318 # define SQLITE_APICALL
319 #endif
320 #ifndef SQLITE_STDCALL
321 # define SQLITE_STDCALL SQLITE_APICALL
322 #endif
323 #ifndef SQLITE_CALLBACK
324 # define SQLITE_CALLBACK
325 #endif
326 #ifndef SQLITE_SYSAPI
327 # define SQLITE_SYSAPI
328 #endif
329 
330 /*
331 ** These no-op macros are used in front of interfaces to mark those
332 ** interfaces as either deprecated or experimental. New applications
333 ** should not use deprecated interfaces - they are supported for backwards
334 ** compatibility only. Application writers should be aware that
335 ** experimental interfaces are subject to change in point releases.
336 **
337 ** These macros used to resolve to various kinds of compiler magic that
338 ** would generate warning messages when they were used. But that
339 ** compiler magic ended up generating such a flurry of bug reports
340 ** that we have taken it all out and gone back to using simple
341 ** noop macros.
342 */
343 #define SQLITE_DEPRECATED
344 #define SQLITE_EXPERIMENTAL
345 
346 /*
347 ** Ensure these symbols were not defined by some previous header file.
348 */
349 #ifdef SQLITE_VERSION
350 # undef SQLITE_VERSION
351 #endif
352 #ifdef SQLITE_VERSION_NUMBER
353 # undef SQLITE_VERSION_NUMBER
354 #endif
355 
356 /*
357 ** CAPI3REF: Compile-Time Library Version Numbers
358 **
359 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
360 ** evaluates to a string literal that is the SQLite version in the
361 ** format "X.Y.Z" where X is the major version number (always 3 for
362 ** SQLite3) and Y is the minor version number and Z is the release number.)^
363 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
364 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
365 ** numbers used in [SQLITE_VERSION].)^
366 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
367 ** be larger than the release from which it is derived. Either Y will
368 ** be held constant and Z will be incremented or else Y will be incremented
369 ** and Z will be reset to zero.
370 **
371 ** Since version 3.6.18, SQLite source code has been stored in the
372 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
373 ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
374 ** a string which identifies a particular check-in of SQLite
375 ** within its configuration management system. ^The SQLITE_SOURCE_ID
376 ** string contains the date and time of the check-in (UTC) and an SHA1
377 ** hash of the entire source tree.
378 **
379 ** See also: [sqlite3_libversion()],
380 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
381 ** [sqlite_version()] and [sqlite_source_id()].
382 */
383 #define SQLITE_VERSION "3.14.1"
384 #define SQLITE_VERSION_NUMBER 3014001
385 #define SQLITE_SOURCE_ID "2016-08-11 18:53:32 a12d8059770df4bca59e321c266410344242bf7b"
386 
387 /*
388 ** CAPI3REF: Run-Time Library Version Numbers
389 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
390 **
391 ** These interfaces provide the same information as the [SQLITE_VERSION],
392 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
393 ** but are associated with the library instead of the header file. ^(Cautious
394 ** programmers might include assert() statements in their application to
395 ** verify that values returned by these interfaces match the macros in
396 ** the header, and thus ensure that the application is
397 ** compiled with matching library and header files.
398 **
399 ** <blockquote><pre>
400 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
401 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
402 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
403 ** </pre></blockquote>)^
404 **
405 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
406 ** macro. ^The sqlite3_libversion() function returns a pointer to the
407 ** to the sqlite3_version[] string constant. The sqlite3_libversion()
408 ** function is provided for use in DLLs since DLL users usually do not have
409 ** direct access to string constants within the DLL. ^The
410 ** sqlite3_libversion_number() function returns an integer equal to
411 ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns
412 ** a pointer to a string constant whose value is the same as the
413 ** [SQLITE_SOURCE_ID] C preprocessor macro.
414 **
415 ** See also: [sqlite_version()] and [sqlite_source_id()].
416 */
417 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
418 SQLITE_API const char *SQLITE_STDCALL sqlite3_libversion(void);
419 SQLITE_API const char *SQLITE_STDCALL sqlite3_sourceid(void);
420 SQLITE_API int SQLITE_STDCALL sqlite3_libversion_number(void);
421 
422 /*
423 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
424 **
425 ** ^The sqlite3_compileoption_used() function returns 0 or 1
426 ** indicating whether the specified option was defined at
427 ** compile time. ^The SQLITE_ prefix may be omitted from the
428 ** option name passed to sqlite3_compileoption_used().
429 **
430 ** ^The sqlite3_compileoption_get() function allows iterating
431 ** over the list of options that were defined at compile time by
432 ** returning the N-th compile time option string. ^If N is out of range,
433 ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
434 ** prefix is omitted from any strings returned by
435 ** sqlite3_compileoption_get().
436 **
437 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
438 ** and sqlite3_compileoption_get() may be omitted by specifying the
439 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
440 **
441 ** See also: SQL functions [sqlite_compileoption_used()] and
442 ** [sqlite_compileoption_get()] and the [compile_options pragma].
443 */
444 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
445 SQLITE_API int SQLITE_STDCALL sqlite3_compileoption_used(const char *zOptName);
446 SQLITE_API const char *SQLITE_STDCALL sqlite3_compileoption_get(int N);
447 #endif
448 
449 /*
450 ** CAPI3REF: Test To See If The Library Is Threadsafe
451 **
452 ** ^The sqlite3_threadsafe() function returns zero if and only if
453 ** SQLite was compiled with mutexing code omitted due to the
454 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
455 **
456 ** SQLite can be compiled with or without mutexes. When
457 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
458 ** are enabled and SQLite is threadsafe. When the
459 ** [SQLITE_THREADSAFE] macro is 0,
460 ** the mutexes are omitted. Without the mutexes, it is not safe
461 ** to use SQLite concurrently from more than one thread.
462 **
463 ** Enabling mutexes incurs a measurable performance penalty.
464 ** So if speed is of utmost importance, it makes sense to disable
465 ** the mutexes. But for maximum safety, mutexes should be enabled.
466 ** ^The default behavior is for mutexes to be enabled.
467 **
468 ** This interface can be used by an application to make sure that the
469 ** version of SQLite that it is linking against was compiled with
470 ** the desired setting of the [SQLITE_THREADSAFE] macro.
471 **
472 ** This interface only reports on the compile-time mutex setting
473 ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
474 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
475 ** can be fully or partially disabled using a call to [sqlite3_config()]
476 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
477 ** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the
478 ** sqlite3_threadsafe() function shows only the compile-time setting of
479 ** thread safety, not any run-time changes to that setting made by
480 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
481 ** is unchanged by calls to sqlite3_config().)^
482 **
483 ** See the [threading mode] documentation for additional information.
484 */
485 SQLITE_API int SQLITE_STDCALL sqlite3_threadsafe(void);
486 
487 /*
488 ** CAPI3REF: Database Connection Handle
489 ** KEYWORDS: {database connection} {database connections}
490 **
491 ** Each open SQLite database is represented by a pointer to an instance of
492 ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
493 ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
494 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
495 ** and [sqlite3_close_v2()] are its destructors. There are many other
496 ** interfaces (such as
497 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
498 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
499 ** sqlite3 object.
500 */
501 typedef struct sqlite3 sqlite3;
502 
503 /*
504 ** CAPI3REF: 64-Bit Integer Types
505 ** KEYWORDS: sqlite_int64 sqlite_uint64
506 **
507 ** Because there is no cross-platform way to specify 64-bit integer types
508 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
509 **
510 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
511 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
512 ** compatibility only.
513 **
514 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
515 ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
516 ** sqlite3_uint64 and sqlite_uint64 types can store integer values
517 ** between 0 and +18446744073709551615 inclusive.
518 */
519 #ifdef SQLITE_INT64_TYPE
520  typedef SQLITE_INT64_TYPE sqlite_int64;
521  typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
522 #elif defined(_MSC_VER) || defined(__BORLANDC__)
523  typedef __int64 sqlite_int64;
524  typedef unsigned __int64 sqlite_uint64;
525 #else
526  typedef long long int sqlite_int64;
527  typedef unsigned long long int sqlite_uint64;
528 #endif
529 typedef sqlite_int64 sqlite3_int64;
530 typedef sqlite_uint64 sqlite3_uint64;
531 
532 /*
533 ** If compiling for a processor that lacks floating point support,
534 ** substitute integer for floating-point.
535 */
536 #ifdef SQLITE_OMIT_FLOATING_POINT
537 # define double sqlite3_int64
538 #endif
539 
540 /*
541 ** CAPI3REF: Closing A Database Connection
542 ** DESTRUCTOR: sqlite3
543 **
544 ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
545 ** for the [sqlite3] object.
546 ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
547 ** the [sqlite3] object is successfully destroyed and all associated
548 ** resources are deallocated.
549 **
550 ** ^If the database connection is associated with unfinalized prepared
551 ** statements or unfinished sqlite3_backup objects then sqlite3_close()
552 ** will leave the database connection open and return [SQLITE_BUSY].
553 ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
554 ** and/or unfinished sqlite3_backups, then the database connection becomes
555 ** an unusable "zombie" which will automatically be deallocated when the
556 ** last prepared statement is finalized or the last sqlite3_backup is
557 ** finished. The sqlite3_close_v2() interface is intended for use with
558 ** host languages that are garbage collected, and where the order in which
559 ** destructors are called is arbitrary.
560 **
561 ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
562 ** [sqlite3_blob_close | close] all [BLOB handles], and
563 ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
564 ** with the [sqlite3] object prior to attempting to close the object. ^If
565 ** sqlite3_close_v2() is called on a [database connection] that still has
566 ** outstanding [prepared statements], [BLOB handles], and/or
567 ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
568 ** of resources is deferred until all [prepared statements], [BLOB handles],
569 ** and [sqlite3_backup] objects are also destroyed.
570 **
571 ** ^If an [sqlite3] object is destroyed while a transaction is open,
572 ** the transaction is automatically rolled back.
573 **
574 ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
575 ** must be either a NULL
576 ** pointer or an [sqlite3] object pointer obtained
577 ** from [sqlite3_open()], [sqlite3_open16()], or
578 ** [sqlite3_open_v2()], and not previously closed.
579 ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
580 ** argument is a harmless no-op.
581 */
582 SQLITE_API int SQLITE_STDCALL sqlite3_close(sqlite3*);
583 SQLITE_API int SQLITE_STDCALL sqlite3_close_v2(sqlite3*);
584 
585 /*
586 ** The type for a callback function.
587 ** This is legacy and deprecated. It is included for historical
588 ** compatibility and is not documented.
589 */
590 typedef int (*sqlite3_callback)(void*,int,char**, char**);
591 
592 /*
593 ** CAPI3REF: One-Step Query Execution Interface
594 ** METHOD: sqlite3
595 **
596 ** The sqlite3_exec() interface is a convenience wrapper around
597 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
598 ** that allows an application to run multiple statements of SQL
599 ** without having to use a lot of C code.
600 **
601 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
602 ** semicolon-separate SQL statements passed into its 2nd argument,
603 ** in the context of the [database connection] passed in as its 1st
604 ** argument. ^If the callback function of the 3rd argument to
605 ** sqlite3_exec() is not NULL, then it is invoked for each result row
606 ** coming out of the evaluated SQL statements. ^The 4th argument to
607 ** sqlite3_exec() is relayed through to the 1st argument of each
608 ** callback invocation. ^If the callback pointer to sqlite3_exec()
609 ** is NULL, then no callback is ever invoked and result rows are
610 ** ignored.
611 **
612 ** ^If an error occurs while evaluating the SQL statements passed into
613 ** sqlite3_exec(), then execution of the current statement stops and
614 ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
615 ** is not NULL then any error message is written into memory obtained
616 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
617 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
618 ** on error message strings returned through the 5th parameter of
619 ** sqlite3_exec() after the error message string is no longer needed.
620 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
621 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
622 ** NULL before returning.
623 **
624 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
625 ** routine returns SQLITE_ABORT without invoking the callback again and
626 ** without running any subsequent SQL statements.
627 **
628 ** ^The 2nd argument to the sqlite3_exec() callback function is the
629 ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
630 ** callback is an array of pointers to strings obtained as if from
631 ** [sqlite3_column_text()], one for each column. ^If an element of a
632 ** result row is NULL then the corresponding string pointer for the
633 ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
634 ** sqlite3_exec() callback is an array of pointers to strings where each
635 ** entry represents the name of corresponding result column as obtained
636 ** from [sqlite3_column_name()].
637 **
638 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
639 ** to an empty string, or a pointer that contains only whitespace and/or
640 ** SQL comments, then no SQL statements are evaluated and the database
641 ** is not changed.
642 **
643 ** Restrictions:
644 **
645 ** <ul>
646 ** <li> The application must ensure that the 1st parameter to sqlite3_exec()
647 ** is a valid and open [database connection].
648 ** <li> The application must not close the [database connection] specified by
649 ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
650 ** <li> The application must not modify the SQL statement text passed into
651 ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
652 ** </ul>
653 */
654 SQLITE_API int SQLITE_STDCALL sqlite3_exec(
655  sqlite3*, /* An open database */
656  const char *sql, /* SQL to be evaluated */
657  int (*callback)(void*,int,char**,char**), /* Callback function */
658  void *, /* 1st argument to callback */
659  char **errmsg /* Error msg written here */
660 );
661 
662 /*
663 ** CAPI3REF: Result Codes
664 ** KEYWORDS: {result code definitions}
665 **
666 ** Many SQLite functions return an integer result code from the set shown
667 ** here in order to indicate success or failure.
668 **
669 ** New error codes may be added in future versions of SQLite.
670 **
671 ** See also: [extended result code definitions]
672 */
673 #define SQLITE_OK 0 /* Successful result */
674 /* beginning-of-error-codes */
675 #define SQLITE_ERROR 1 /* SQL error or missing database */
676 #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
677 #define SQLITE_PERM 3 /* Access permission denied */
678 #define SQLITE_ABORT 4 /* Callback routine requested an abort */
679 #define SQLITE_BUSY 5 /* The database file is locked */
680 #define SQLITE_LOCKED 6 /* A table in the database is locked */
681 #define SQLITE_NOMEM 7 /* A malloc() failed */
682 #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
683 #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
684 #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
685 #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
686 #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
687 #define SQLITE_FULL 13 /* Insertion failed because database is full */
688 #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
689 #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
690 #define SQLITE_EMPTY 16 /* Database is empty */
691 #define SQLITE_SCHEMA 17 /* The database schema changed */
692 #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
693 #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
694 #define SQLITE_MISMATCH 20 /* Data type mismatch */
695 #define SQLITE_MISUSE 21 /* Library used incorrectly */
696 #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
697 #define SQLITE_AUTH 23 /* Authorization denied */
698 #define SQLITE_FORMAT 24 /* Auxiliary database format error */
699 #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
700 #define SQLITE_NOTADB 26 /* File opened that is not a database file */
701 #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
702 #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
703 #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
704 #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
705 /* end-of-error-codes */
706 
707 /*
708 ** CAPI3REF: Extended Result Codes
709 ** KEYWORDS: {extended result code definitions}
710 **
711 ** In its default configuration, SQLite API routines return one of 30 integer
712 ** [result codes]. However, experience has shown that many of
713 ** these result codes are too coarse-grained. They do not provide as
714 ** much information about problems as programmers might like. In an effort to
715 ** address this, newer versions of SQLite (version 3.3.8 and later) include
716 ** support for additional result codes that provide more detailed information
717 ** about errors. These [extended result codes] are enabled or disabled
718 ** on a per database connection basis using the
719 ** [sqlite3_extended_result_codes()] API. Or, the extended code for
720 ** the most recent error can be obtained using
721 ** [sqlite3_extended_errcode()].
722 */
723 #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
724 #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
725 #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
726 #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
727 #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
728 #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
729 #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
730 #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
731 #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
732 #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
733 #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
734 #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
735 #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
736 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
737 #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
738 #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
739 #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
740 #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
741 #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
742 #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
743 #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
744 #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
745 #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
746 #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
747 #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
748 #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
749 #define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8))
750 #define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8))
751 #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
752 #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
753 #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
754 #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
755 #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
756 #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
757 #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
758 #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
759 #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
760 #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
761 #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
762 #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
763 #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
764 #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
765 #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
766 #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
767 #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
768 #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
769 #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
770 #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
771 #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
772 #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
773 #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
774 #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
775 #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
776 #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
777 #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
778 #define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8))
779 
780 /*
781 ** CAPI3REF: Flags For File Open Operations
782 **
783 ** These bit values are intended for use in the
784 ** 3rd parameter to the [sqlite3_open_v2()] interface and
785 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
786 */
787 #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
788 #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
789 #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
790 #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
791 #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
792 #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
793 #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
794 #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
795 #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
796 #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
797 #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
798 #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
799 #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
800 #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
801 #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
802 #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
803 #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
804 #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
805 #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
806 #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
807 
808 /* Reserved: 0x00F00000 */
809 
810 /*
811 ** CAPI3REF: Device Characteristics
812 **
813 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
814 ** object returns an integer which is a vector of these
815 ** bit values expressing I/O characteristics of the mass storage
816 ** device that holds the file that the [sqlite3_io_methods]
817 ** refers to.
818 **
819 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
820 ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
821 ** mean that writes of blocks that are nnn bytes in size and
822 ** are aligned to an address which is an integer multiple of
823 ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
824 ** that when data is appended to a file, the data is appended
825 ** first then the size of the file is extended, never the other
826 ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
827 ** information is written to disk in the same order as calls
828 ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
829 ** after reboot following a crash or power loss, the only bytes in a
830 ** file that were written at the application level might have changed
831 ** and that adjacent bytes, even bytes within the same sector are
832 ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
833 ** flag indicate that a file cannot be deleted when open. The
834 ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
835 ** read-only media and cannot be changed even by processes with
836 ** elevated privileges.
837 */
838 #define SQLITE_IOCAP_ATOMIC 0x00000001
839 #define SQLITE_IOCAP_ATOMIC512 0x00000002
840 #define SQLITE_IOCAP_ATOMIC1K 0x00000004
841 #define SQLITE_IOCAP_ATOMIC2K 0x00000008
842 #define SQLITE_IOCAP_ATOMIC4K 0x00000010
843 #define SQLITE_IOCAP_ATOMIC8K 0x00000020
844 #define SQLITE_IOCAP_ATOMIC16K 0x00000040
845 #define SQLITE_IOCAP_ATOMIC32K 0x00000080
846 #define SQLITE_IOCAP_ATOMIC64K 0x00000100
847 #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
848 #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
849 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
850 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
851 #define SQLITE_IOCAP_IMMUTABLE 0x00002000
852 
853 /*
854 ** CAPI3REF: File Locking Levels
855 **
856 ** SQLite uses one of these integer values as the second
857 ** argument to calls it makes to the xLock() and xUnlock() methods
858 ** of an [sqlite3_io_methods] object.
859 */
860 #define SQLITE_LOCK_NONE 0
861 #define SQLITE_LOCK_SHARED 1
862 #define SQLITE_LOCK_RESERVED 2
863 #define SQLITE_LOCK_PENDING 3
864 #define SQLITE_LOCK_EXCLUSIVE 4
865 
866 /*
867 ** CAPI3REF: Synchronization Type Flags
868 **
869 ** When SQLite invokes the xSync() method of an
870 ** [sqlite3_io_methods] object it uses a combination of
871 ** these integer values as the second argument.
872 **
873 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
874 ** sync operation only needs to flush data to mass storage. Inode
875 ** information need not be flushed. If the lower four bits of the flag
876 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
877 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
878 ** to use Mac OS X style fullsync instead of fsync().
879 **
880 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
881 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
882 ** settings. The [synchronous pragma] determines when calls to the
883 ** xSync VFS method occur and applies uniformly across all platforms.
884 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
885 ** energetic or rigorous or forceful the sync operations are and
886 ** only make a difference on Mac OSX for the default SQLite code.
887 ** (Third-party VFS implementations might also make the distinction
888 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
889 ** operating systems natively supported by SQLite, only Mac OSX
890 ** cares about the difference.)
891 */
892 #define SQLITE_SYNC_NORMAL 0x00002
893 #define SQLITE_SYNC_FULL 0x00003
894 #define SQLITE_SYNC_DATAONLY 0x00010
895 
896 /*
897 ** CAPI3REF: OS Interface Open File Handle
898 **
899 ** An [sqlite3_file] object represents an open file in the
900 ** [sqlite3_vfs | OS interface layer]. Individual OS interface
901 ** implementations will
902 ** want to subclass this object by appending additional fields
903 ** for their own use. The pMethods entry is a pointer to an
904 ** [sqlite3_io_methods] object that defines methods for performing
905 ** I/O operations on the open file.
906 */
907 typedef struct sqlite3_file sqlite3_file;
908 struct sqlite3_file {
909  const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
910 };
911 
912 /*
913 ** CAPI3REF: OS Interface File Virtual Methods Object
914 **
915 ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
916 ** [sqlite3_file] object (or, more commonly, a subclass of the
917 ** [sqlite3_file] object) with a pointer to an instance of this object.
918 ** This object defines the methods used to perform various operations
919 ** against the open file represented by the [sqlite3_file] object.
920 **
921 ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
922 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
923 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
924 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
925 ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
926 ** to NULL.
927 **
928 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
929 ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
930 ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
931 ** flag may be ORed in to indicate that only the data of the file
932 ** and not its inode needs to be synced.
933 **
934 ** The integer values to xLock() and xUnlock() are one of
935 ** <ul>
936 ** <li> [SQLITE_LOCK_NONE],
937 ** <li> [SQLITE_LOCK_SHARED],
938 ** <li> [SQLITE_LOCK_RESERVED],
939 ** <li> [SQLITE_LOCK_PENDING], or
940 ** <li> [SQLITE_LOCK_EXCLUSIVE].
941 ** </ul>
942 ** xLock() increases the lock. xUnlock() decreases the lock.
943 ** The xCheckReservedLock() method checks whether any database connection,
944 ** either in this process or in some other process, is holding a RESERVED,
945 ** PENDING, or EXCLUSIVE lock on the file. It returns true
946 ** if such a lock exists and false otherwise.
947 **
948 ** The xFileControl() method is a generic interface that allows custom
949 ** VFS implementations to directly control an open file using the
950 ** [sqlite3_file_control()] interface. The second "op" argument is an
951 ** integer opcode. The third argument is a generic pointer intended to
952 ** point to a structure that may contain arguments or space in which to
953 ** write return values. Potential uses for xFileControl() might be
954 ** functions to enable blocking locks with timeouts, to change the
955 ** locking strategy (for example to use dot-file locks), to inquire
956 ** about the status of a lock, or to break stale locks. The SQLite
957 ** core reserves all opcodes less than 100 for its own use.
958 ** A [file control opcodes | list of opcodes] less than 100 is available.
959 ** Applications that define a custom xFileControl method should use opcodes
960 ** greater than 100 to avoid conflicts. VFS implementations should
961 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
962 ** recognize.
963 **
964 ** The xSectorSize() method returns the sector size of the
965 ** device that underlies the file. The sector size is the
966 ** minimum write that can be performed without disturbing
967 ** other bytes in the file. The xDeviceCharacteristics()
968 ** method returns a bit vector describing behaviors of the
969 ** underlying device:
970 **
971 ** <ul>
972 ** <li> [SQLITE_IOCAP_ATOMIC]
973 ** <li> [SQLITE_IOCAP_ATOMIC512]
974 ** <li> [SQLITE_IOCAP_ATOMIC1K]
975 ** <li> [SQLITE_IOCAP_ATOMIC2K]
976 ** <li> [SQLITE_IOCAP_ATOMIC4K]
977 ** <li> [SQLITE_IOCAP_ATOMIC8K]
978 ** <li> [SQLITE_IOCAP_ATOMIC16K]
979 ** <li> [SQLITE_IOCAP_ATOMIC32K]
980 ** <li> [SQLITE_IOCAP_ATOMIC64K]
981 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
982 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
983 ** </ul>
984 **
985 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
986 ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
987 ** mean that writes of blocks that are nnn bytes in size and
988 ** are aligned to an address which is an integer multiple of
989 ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
990 ** that when data is appended to a file, the data is appended
991 ** first then the size of the file is extended, never the other
992 ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
993 ** information is written to disk in the same order as calls
994 ** to xWrite().
995 **
996 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
997 ** in the unread portions of the buffer with zeros. A VFS that
998 ** fails to zero-fill short reads might seem to work. However,
999 ** failure to zero-fill short reads will eventually lead to
1000 ** database corruption.
1001 */
1002 typedef struct sqlite3_io_methods sqlite3_io_methods;
1003 struct sqlite3_io_methods {
1004  int iVersion;
1005  int (*xClose)(sqlite3_file*);
1006  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1007  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1008  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1009  int (*xSync)(sqlite3_file*, int flags);
1010  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1011  int (*xLock)(sqlite3_file*, int);
1012  int (*xUnlock)(sqlite3_file*, int);
1013  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1014  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1015  int (*xSectorSize)(sqlite3_file*);
1016  int (*xDeviceCharacteristics)(sqlite3_file*);
1017  /* Methods above are valid for version 1 */
1018  int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1019  int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1020  void (*xShmBarrier)(sqlite3_file*);
1021  int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1022  /* Methods above are valid for version 2 */
1023  int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
1024  int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
1025  /* Methods above are valid for version 3 */
1026  /* Additional methods may be added in future releases */
1027 };
1028 
1029 /*
1030 ** CAPI3REF: Standard File Control Opcodes
1031 ** KEYWORDS: {file control opcodes} {file control opcode}
1032 **
1033 ** These integer constants are opcodes for the xFileControl method
1034 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1035 ** interface.
1036 **
1037 ** <ul>
1038 ** <li>[[SQLITE_FCNTL_LOCKSTATE]]
1039 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
1040 ** opcode causes the xFileControl method to write the current state of
1041 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1042 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1043 ** into an integer that the pArg argument points to. This capability
1044 ** is used during testing and is only available when the SQLITE_TEST
1045 ** compile-time option is used.
1046 **
1047 ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
1048 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1049 ** layer a hint of how large the database file will grow to be during the
1050 ** current transaction. This hint is not guaranteed to be accurate but it
1051 ** is often close. The underlying VFS might choose to preallocate database
1052 ** file space based on this hint in order to help writes to the database
1053 ** file run faster.
1054 **
1055 ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
1056 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1057 ** extends and truncates the database file in chunks of a size specified
1058 ** by the user. The fourth argument to [sqlite3_file_control()] should
1059 ** point to an integer (type int) containing the new chunk-size to use
1060 ** for the nominated database. Allocating database file space in large
1061 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
1062 ** improve performance on some systems.
1063 **
1064 ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
1065 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1066 ** to the [sqlite3_file] object associated with a particular database
1067 ** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER].
1068 **
1069 ** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
1070 ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
1071 ** to the [sqlite3_file] object associated with the journal file (either
1072 ** the [rollback journal] or the [write-ahead log]) for a particular database
1073 ** connection. See also [SQLITE_FCNTL_FILE_POINTER].
1074 **
1075 ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1076 ** No longer in use.
1077 **
1078 ** <li>[[SQLITE_FCNTL_SYNC]]
1079 ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
1080 ** sent to the VFS immediately before the xSync method is invoked on a
1081 ** database file descriptor. Or, if the xSync method is not invoked
1082 ** because the user has configured SQLite with
1083 ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
1084 ** of the xSync method. In most cases, the pointer argument passed with
1085 ** this file-control is NULL. However, if the database file is being synced
1086 ** as part of a multi-database commit, the argument points to a nul-terminated
1087 ** string containing the transactions master-journal file name. VFSes that
1088 ** do not need this signal should silently ignore this opcode. Applications
1089 ** should not call [sqlite3_file_control()] with this opcode as doing so may
1090 ** disrupt the operation of the specialized VFSes that do require it.
1091 **
1092 ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
1093 ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
1094 ** and sent to the VFS after a transaction has been committed immediately
1095 ** but before the database is unlocked. VFSes that do not need this signal
1096 ** should silently ignore this opcode. Applications should not call
1097 ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
1098 ** operation of the specialized VFSes that do require it.
1099 **
1100 ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1101 ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1102 ** retry counts and intervals for certain disk I/O operations for the
1103 ** windows [VFS] in order to provide robustness in the presence of
1104 ** anti-virus programs. By default, the windows VFS will retry file read,
1105 ** file write, and file delete operations up to 10 times, with a delay
1106 ** of 25 milliseconds before the first retry and with the delay increasing
1107 ** by an additional 25 milliseconds with each subsequent retry. This
1108 ** opcode allows these two values (10 retries and 25 milliseconds of delay)
1109 ** to be adjusted. The values are changed for all database connections
1110 ** within the same process. The argument is a pointer to an array of two
1111 ** integers where the first integer i the new retry count and the second
1112 ** integer is the delay. If either integer is negative, then the setting
1113 ** is not changed but instead the prior value of that setting is written
1114 ** into the array entry, allowing the current retry settings to be
1115 ** interrogated. The zDbName parameter is ignored.
1116 **
1117 ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1118 ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1119 ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
1120 ** write ahead log and shared memory files used for transaction control
1121 ** are automatically deleted when the latest connection to the database
1122 ** closes. Setting persistent WAL mode causes those files to persist after
1123 ** close. Persisting the files is useful when other processes that do not
1124 ** have write permission on the directory containing the database file want
1125 ** to read the database file, as the WAL and shared memory files must exist
1126 ** in order for the database to be readable. The fourth parameter to
1127 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1128 ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1129 ** WAL mode. If the integer is -1, then it is overwritten with the current
1130 ** WAL persistence setting.
1131 **
1132 ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1133 ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1134 ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
1135 ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1136 ** xDeviceCharacteristics methods. The fourth parameter to
1137 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1138 ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1139 ** mode. If the integer is -1, then it is overwritten with the current
1140 ** zero-damage mode setting.
1141 **
1142 ** <li>[[SQLITE_FCNTL_OVERWRITE]]
1143 ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1144 ** a write transaction to indicate that, unless it is rolled back for some
1145 ** reason, the entire database file will be overwritten by the current
1146 ** transaction. This is used by VACUUM operations.
1147 **
1148 ** <li>[[SQLITE_FCNTL_VFSNAME]]
1149 ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1150 ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
1151 ** final bottom-level VFS are written into memory obtained from
1152 ** [sqlite3_malloc()] and the result is stored in the char* variable
1153 ** that the fourth parameter of [sqlite3_file_control()] points to.
1154 ** The caller is responsible for freeing the memory when done. As with
1155 ** all file-control actions, there is no guarantee that this will actually
1156 ** do anything. Callers should initialize the char* variable to a NULL
1157 ** pointer in case this file-control is not implemented. This file-control
1158 ** is intended for diagnostic use only.
1159 **
1160 ** <li>[[SQLITE_FCNTL_VFS_POINTER]]
1161 ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
1162 ** [VFSes] currently in use. ^(The argument X in
1163 ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
1164 ** of type "[sqlite3_vfs] **". This opcodes will set *X
1165 ** to a pointer to the top-level VFS.)^
1166 ** ^When there are multiple VFS shims in the stack, this opcode finds the
1167 ** upper-most shim only.
1168 **
1169 ** <li>[[SQLITE_FCNTL_PRAGMA]]
1170 ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
1171 ** file control is sent to the open [sqlite3_file] object corresponding
1172 ** to the database file to which the pragma statement refers. ^The argument
1173 ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1174 ** pointers to strings (char**) in which the second element of the array
1175 ** is the name of the pragma and the third element is the argument to the
1176 ** pragma or NULL if the pragma has no argument. ^The handler for an
1177 ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1178 ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1179 ** or the equivalent and that string will become the result of the pragma or
1180 ** the error message if the pragma fails. ^If the
1181 ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
1182 ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
1183 ** file control returns [SQLITE_OK], then the parser assumes that the
1184 ** VFS has handled the PRAGMA itself and the parser generates a no-op
1185 ** prepared statement if result string is NULL, or that returns a copy
1186 ** of the result string if the string is non-NULL.
1187 ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1188 ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1189 ** that the VFS encountered an error while handling the [PRAGMA] and the
1190 ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
1191 ** file control occurs at the beginning of pragma statement analysis and so
1192 ** it is able to override built-in [PRAGMA] statements.
1193 **
1194 ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
1195 ** ^The [SQLITE_FCNTL_BUSYHANDLER]
1196 ** file-control may be invoked by SQLite on the database file handle
1197 ** shortly after it is opened in order to provide a custom VFS with access
1198 ** to the connections busy-handler callback. The argument is of type (void **)
1199 ** - an array of two (void *) values. The first (void *) actually points
1200 ** to a function of type (int (*)(void *)). In order to invoke the connections
1201 ** busy-handler, this function should be invoked with the second (void *) in
1202 ** the array as the only argument. If it returns non-zero, then the operation
1203 ** should be retried. If it returns zero, the custom VFS should abandon the
1204 ** current operation.
1205 **
1206 ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
1207 ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
1208 ** to have SQLite generate a
1209 ** temporary filename using the same algorithm that is followed to generate
1210 ** temporary filenames for TEMP tables and other internal uses. The
1211 ** argument should be a char** which will be filled with the filename
1212 ** written into memory obtained from [sqlite3_malloc()]. The caller should
1213 ** invoke [sqlite3_free()] on the result to avoid a memory leak.
1214 **
1215 ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
1216 ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
1217 ** maximum number of bytes that will be used for memory-mapped I/O.
1218 ** The argument is a pointer to a value of type sqlite3_int64 that
1219 ** is an advisory maximum number of bytes in the file to memory map. The
1220 ** pointer is overwritten with the old value. The limit is not changed if
1221 ** the value originally pointed to is negative, and so the current limit
1222 ** can be queried by passing in a pointer to a negative number. This
1223 ** file-control is used internally to implement [PRAGMA mmap_size].
1224 **
1225 ** <li>[[SQLITE_FCNTL_TRACE]]
1226 ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
1227 ** to the VFS about what the higher layers of the SQLite stack are doing.
1228 ** This file control is used by some VFS activity tracing [shims].
1229 ** The argument is a zero-terminated string. Higher layers in the
1230 ** SQLite stack may generate instances of this file control if
1231 ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
1232 **
1233 ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
1234 ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
1235 ** pointer to an integer and it writes a boolean into that integer depending
1236 ** on whether or not the file has been renamed, moved, or deleted since it
1237 ** was first opened.
1238 **
1239 ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
1240 ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
1241 ** opcode causes the xFileControl method to swap the file handle with the one
1242 ** pointed to by the pArg argument. This capability is used during testing
1243 ** and only needs to be supported when SQLITE_TEST is defined.
1244 **
1245 ** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
1246 ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
1247 ** be advantageous to block on the next WAL lock if the lock is not immediately
1248 ** available. The WAL subsystem issues this signal during rare
1249 ** circumstances in order to fix a problem with priority inversion.
1250 ** Applications should <em>not</em> use this file-control.
1251 **
1252 ** <li>[[SQLITE_FCNTL_ZIPVFS]]
1253 ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
1254 ** VFS should return SQLITE_NOTFOUND for this opcode.
1255 **
1256 ** <li>[[SQLITE_FCNTL_RBU]]
1257 ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
1258 ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
1259 ** this opcode.
1260 ** </ul>
1261 */
1262 #define SQLITE_FCNTL_LOCKSTATE 1
1263 #define SQLITE_FCNTL_GET_LOCKPROXYFILE 2
1264 #define SQLITE_FCNTL_SET_LOCKPROXYFILE 3
1265 #define SQLITE_FCNTL_LAST_ERRNO 4
1266 #define SQLITE_FCNTL_SIZE_HINT 5
1267 #define SQLITE_FCNTL_CHUNK_SIZE 6
1268 #define SQLITE_FCNTL_FILE_POINTER 7
1269 #define SQLITE_FCNTL_SYNC_OMITTED 8
1270 #define SQLITE_FCNTL_WIN32_AV_RETRY 9
1271 #define SQLITE_FCNTL_PERSIST_WAL 10
1272 #define SQLITE_FCNTL_OVERWRITE 11
1273 #define SQLITE_FCNTL_VFSNAME 12
1274 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
1275 #define SQLITE_FCNTL_PRAGMA 14
1276 #define SQLITE_FCNTL_BUSYHANDLER 15
1277 #define SQLITE_FCNTL_TEMPFILENAME 16
1278 #define SQLITE_FCNTL_MMAP_SIZE 18
1279 #define SQLITE_FCNTL_TRACE 19
1280 #define SQLITE_FCNTL_HAS_MOVED 20
1281 #define SQLITE_FCNTL_SYNC 21
1282 #define SQLITE_FCNTL_COMMIT_PHASETWO 22
1283 #define SQLITE_FCNTL_WIN32_SET_HANDLE 23
1284 #define SQLITE_FCNTL_WAL_BLOCK 24
1285 #define SQLITE_FCNTL_ZIPVFS 25
1286 #define SQLITE_FCNTL_RBU 26
1287 #define SQLITE_FCNTL_VFS_POINTER 27
1288 #define SQLITE_FCNTL_JOURNAL_POINTER 28
1289 
1290 /* deprecated names */
1291 #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
1292 #define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE
1293 #define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO
1294 
1295 
1296 /*
1297 ** CAPI3REF: Mutex Handle
1298 **
1299 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1300 ** abstract type for a mutex object. The SQLite core never looks
1301 ** at the internal representation of an [sqlite3_mutex]. It only
1302 ** deals with pointers to the [sqlite3_mutex] object.
1303 **
1304 ** Mutexes are created using [sqlite3_mutex_alloc()].
1305 */
1306 typedef struct sqlite3_mutex sqlite3_mutex;
1307 
1308 /*
1309 ** CAPI3REF: Loadable Extension Thunk
1310 **
1311 ** A pointer to the opaque sqlite3_api_routines structure is passed as
1312 ** the third parameter to entry points of [loadable extensions]. This
1313 ** structure must be typedefed in order to work around compiler warnings
1314 ** on some platforms.
1315 */
1316 typedef struct sqlite3_api_routines sqlite3_api_routines;
1317 
1318 /*
1319 ** CAPI3REF: OS Interface Object
1320 **
1321 ** An instance of the sqlite3_vfs object defines the interface between
1322 ** the SQLite core and the underlying operating system. The "vfs"
1323 ** in the name of the object stands for "virtual file system". See
1324 ** the [VFS | VFS documentation] for further information.
1325 **
1326 ** The value of the iVersion field is initially 1 but may be larger in
1327 ** future versions of SQLite. Additional fields may be appended to this
1328 ** object when the iVersion value is increased. Note that the structure
1329 ** of the sqlite3_vfs object changes in the transaction between
1330 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1331 ** modified.
1332 **
1333 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1334 ** structure used by this VFS. mxPathname is the maximum length of
1335 ** a pathname in this VFS.
1336 **
1337 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1338 ** the pNext pointer. The [sqlite3_vfs_register()]
1339 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1340 ** in a thread-safe way. The [sqlite3_vfs_find()] interface
1341 ** searches the list. Neither the application code nor the VFS
1342 ** implementation should use the pNext pointer.
1343 **
1344 ** The pNext field is the only field in the sqlite3_vfs
1345 ** structure that SQLite will ever modify. SQLite will only access
1346 ** or modify this field while holding a particular static mutex.
1347 ** The application should never modify anything within the sqlite3_vfs
1348 ** object once the object has been registered.
1349 **
1350 ** The zName field holds the name of the VFS module. The name must
1351 ** be unique across all VFS modules.
1352 **
1353 ** [[sqlite3_vfs.xOpen]]
1354 ** ^SQLite guarantees that the zFilename parameter to xOpen
1355 ** is either a NULL pointer or string obtained
1356 ** from xFullPathname() with an optional suffix added.
1357 ** ^If a suffix is added to the zFilename parameter, it will
1358 ** consist of a single "-" character followed by no more than
1359 ** 11 alphanumeric and/or "-" characters.
1360 ** ^SQLite further guarantees that
1361 ** the string will be valid and unchanged until xClose() is
1362 ** called. Because of the previous sentence,
1363 ** the [sqlite3_file] can safely store a pointer to the
1364 ** filename if it needs to remember the filename for some reason.
1365 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1366 ** must invent its own temporary name for the file. ^Whenever the
1367 ** xFilename parameter is NULL it will also be the case that the
1368 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1369 **
1370 ** The flags argument to xOpen() includes all bits set in
1371 ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
1372 ** or [sqlite3_open16()] is used, then flags includes at least
1373 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1374 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1375 ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
1376 **
1377 ** ^(SQLite will also add one of the following flags to the xOpen()
1378 ** call, depending on the object being opened:
1379 **
1380 ** <ul>
1381 ** <li> [SQLITE_OPEN_MAIN_DB]
1382 ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
1383 ** <li> [SQLITE_OPEN_TEMP_DB]
1384 ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
1385 ** <li> [SQLITE_OPEN_TRANSIENT_DB]
1386 ** <li> [SQLITE_OPEN_SUBJOURNAL]
1387 ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
1388 ** <li> [SQLITE_OPEN_WAL]
1389 ** </ul>)^
1390 **
1391 ** The file I/O implementation can use the object type flags to
1392 ** change the way it deals with files. For example, an application
1393 ** that does not care about crash recovery or rollback might make
1394 ** the open of a journal file a no-op. Writes to this journal would
1395 ** also be no-ops, and any attempt to read the journal would return
1396 ** SQLITE_IOERR. Or the implementation might recognize that a database
1397 ** file will be doing page-aligned sector reads and writes in a random
1398 ** order and set up its I/O subsystem accordingly.
1399 **
1400 ** SQLite might also add one of the following flags to the xOpen method:
1401 **
1402 ** <ul>
1403 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1404 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1405 ** </ul>
1406 **
1407 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1408 ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
1409 ** will be set for TEMP databases and their journals, transient
1410 ** databases, and subjournals.
1411 **
1412 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1413 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1414 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1415 ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1416 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1417 ** be created, and that it is an error if it already exists.
1418 ** It is <i>not</i> used to indicate the file should be opened
1419 ** for exclusive access.
1420 **
1421 ** ^At least szOsFile bytes of memory are allocated by SQLite
1422 ** to hold the [sqlite3_file] structure passed as the third
1423 ** argument to xOpen. The xOpen method does not have to
1424 ** allocate the structure; it should just fill it in. Note that
1425 ** the xOpen method must set the sqlite3_file.pMethods to either
1426 ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
1427 ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
1428 ** element will be valid after xOpen returns regardless of the success
1429 ** or failure of the xOpen call.
1430 **
1431 ** [[sqlite3_vfs.xAccess]]
1432 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1433 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1434 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1435 ** to test whether a file is at least readable. The file can be a
1436 ** directory.
1437 **
1438 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1439 ** output buffer xFullPathname. The exact size of the output buffer
1440 ** is also passed as a parameter to both methods. If the output buffer
1441 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1442 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1443 ** to prevent this by setting mxPathname to a sufficiently large value.
1444 **
1445 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1446 ** interfaces are not strictly a part of the filesystem, but they are
1447 ** included in the VFS structure for completeness.
1448 ** The xRandomness() function attempts to return nBytes bytes
1449 ** of good-quality randomness into zOut. The return value is
1450 ** the actual number of bytes of randomness obtained.
1451 ** The xSleep() method causes the calling thread to sleep for at
1452 ** least the number of microseconds given. ^The xCurrentTime()
1453 ** method returns a Julian Day Number for the current date and time as
1454 ** a floating point value.
1455 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1456 ** Day Number multiplied by 86400000 (the number of milliseconds in
1457 ** a 24-hour day).
1458 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1459 ** date and time if that method is available (if iVersion is 2 or
1460 ** greater and the function pointer is not NULL) and will fall back
1461 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1462 **
1463 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1464 ** are not used by the SQLite core. These optional interfaces are provided
1465 ** by some VFSes to facilitate testing of the VFS code. By overriding
1466 ** system calls with functions under its control, a test program can
1467 ** simulate faults and error conditions that would otherwise be difficult
1468 ** or impossible to induce. The set of system calls that can be overridden
1469 ** varies from one VFS to another, and from one version of the same VFS to the
1470 ** next. Applications that use these interfaces must be prepared for any
1471 ** or all of these interfaces to be NULL or for their behavior to change
1472 ** from one release to the next. Applications must not attempt to access
1473 ** any of these methods if the iVersion of the VFS is less than 3.
1474 */
1475 typedef struct sqlite3_vfs sqlite3_vfs;
1476 typedef void (*sqlite3_syscall_ptr)(void);
1477 struct sqlite3_vfs {
1478  int iVersion; /* Structure version number (currently 3) */
1479  int szOsFile; /* Size of subclassed sqlite3_file */
1480  int mxPathname; /* Maximum file pathname length */
1481  sqlite3_vfs *pNext; /* Next registered VFS */
1482  const char *zName; /* Name of this virtual file system */
1483  void *pAppData; /* Pointer to application-specific data */
1484  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1485  int flags, int *pOutFlags);
1486  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1487  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1488  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1489  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1490  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1491  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1492  void (*xDlClose)(sqlite3_vfs*, void*);
1493  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1494  int (*xSleep)(sqlite3_vfs*, int microseconds);
1495  int (*xCurrentTime)(sqlite3_vfs*, double*);
1496  int (*xGetLastError)(sqlite3_vfs*, int, char *);
1497  /*
1498  ** The methods above are in version 1 of the sqlite_vfs object
1499  ** definition. Those that follow are added in version 2 or later
1500  */
1501  int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1502  /*
1503  ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1504  ** Those below are for version 3 and greater.
1505  */
1506  int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1507  sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1508  const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1509  /*
1510  ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1511  ** New fields may be appended in future versions. The iVersion
1512  ** value will increment whenever this happens.
1513  */
1514 };
1515 
1516 /*
1517 ** CAPI3REF: Flags for the xAccess VFS method
1518 **
1519 ** These integer constants can be used as the third parameter to
1520 ** the xAccess method of an [sqlite3_vfs] object. They determine
1521 ** what kind of permissions the xAccess method is looking for.
1522 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1523 ** simply checks whether the file exists.
1524 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1525 ** checks whether the named directory is both readable and writable
1526 ** (in other words, if files can be added, removed, and renamed within
1527 ** the directory).
1528 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1529 ** [temp_store_directory pragma], though this could change in a future
1530 ** release of SQLite.
1531 ** With SQLITE_ACCESS_READ, the xAccess method
1532 ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
1533 ** currently unused, though it might be used in a future release of
1534 ** SQLite.
1535 */
1536 #define SQLITE_ACCESS_EXISTS 0
1537 #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
1538 #define SQLITE_ACCESS_READ 2 /* Unused */
1539 
1540 /*
1541 ** CAPI3REF: Flags for the xShmLock VFS method
1542 **
1543 ** These integer constants define the various locking operations
1544 ** allowed by the xShmLock method of [sqlite3_io_methods]. The
1545 ** following are the only legal combinations of flags to the
1546 ** xShmLock method:
1547 **
1548 ** <ul>
1549 ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1550 ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1551 ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1552 ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1553 ** </ul>
1554 **
1555 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1556 ** was given on the corresponding lock.
1557 **
1558 ** The xShmLock method can transition between unlocked and SHARED or
1559 ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
1560 ** and EXCLUSIVE.
1561 */
1562 #define SQLITE_SHM_UNLOCK 1
1563 #define SQLITE_SHM_LOCK 2
1564 #define SQLITE_SHM_SHARED 4
1565 #define SQLITE_SHM_EXCLUSIVE 8
1566 
1567 /*
1568 ** CAPI3REF: Maximum xShmLock index
1569 **
1570 ** The xShmLock method on [sqlite3_io_methods] may use values
1571 ** between 0 and this upper bound as its "offset" argument.
1572 ** The SQLite core will never attempt to acquire or release a
1573 ** lock outside of this range
1574 */
1575 #define SQLITE_SHM_NLOCK 8
1576 
1577 
1578 /*
1579 ** CAPI3REF: Initialize The SQLite Library
1580 **
1581 ** ^The sqlite3_initialize() routine initializes the
1582 ** SQLite library. ^The sqlite3_shutdown() routine
1583 ** deallocates any resources that were allocated by sqlite3_initialize().
1584 ** These routines are designed to aid in process initialization and
1585 ** shutdown on embedded systems. Workstation applications using
1586 ** SQLite normally do not need to invoke either of these routines.
1587 **
1588 ** A call to sqlite3_initialize() is an "effective" call if it is
1589 ** the first time sqlite3_initialize() is invoked during the lifetime of
1590 ** the process, or if it is the first time sqlite3_initialize() is invoked
1591 ** following a call to sqlite3_shutdown(). ^(Only an effective call
1592 ** of sqlite3_initialize() does any initialization. All other calls
1593 ** are harmless no-ops.)^
1594 **
1595 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1596 ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
1597 ** an effective call to sqlite3_shutdown() does any deinitialization.
1598 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1599 **
1600 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1601 ** is not. The sqlite3_shutdown() interface must only be called from a
1602 ** single thread. All open [database connections] must be closed and all
1603 ** other SQLite resources must be deallocated prior to invoking
1604 ** sqlite3_shutdown().
1605 **
1606 ** Among other things, ^sqlite3_initialize() will invoke
1607 ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
1608 ** will invoke sqlite3_os_end().
1609 **
1610 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1611 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1612 ** the library (perhaps it is unable to allocate a needed resource such
1613 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1614 **
1615 ** ^The sqlite3_initialize() routine is called internally by many other
1616 ** SQLite interfaces so that an application usually does not need to
1617 ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
1618 ** calls sqlite3_initialize() so the SQLite library will be automatically
1619 ** initialized when [sqlite3_open()] is called if it has not be initialized
1620 ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1621 ** compile-time option, then the automatic calls to sqlite3_initialize()
1622 ** are omitted and the application must call sqlite3_initialize() directly
1623 ** prior to using any other SQLite interface. For maximum portability,
1624 ** it is recommended that applications always invoke sqlite3_initialize()
1625 ** directly prior to using any other SQLite interface. Future releases
1626 ** of SQLite may require this. In other words, the behavior exhibited
1627 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1628 ** default behavior in some future release of SQLite.
1629 **
1630 ** The sqlite3_os_init() routine does operating-system specific
1631 ** initialization of the SQLite library. The sqlite3_os_end()
1632 ** routine undoes the effect of sqlite3_os_init(). Typical tasks
1633 ** performed by these routines include allocation or deallocation
1634 ** of static resources, initialization of global variables,
1635 ** setting up a default [sqlite3_vfs] module, or setting up
1636 ** a default configuration using [sqlite3_config()].
1637 **
1638 ** The application should never invoke either sqlite3_os_init()
1639 ** or sqlite3_os_end() directly. The application should only invoke
1640 ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
1641 ** interface is called automatically by sqlite3_initialize() and
1642 ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
1643 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1644 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1645 ** When [custom builds | built for other platforms]
1646 ** (using the [SQLITE_OS_OTHER=1] compile-time
1647 ** option) the application must supply a suitable implementation for
1648 ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
1649 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1650 ** must return [SQLITE_OK] on success and some other [error code] upon
1651 ** failure.
1652 */
1653 SQLITE_API int SQLITE_STDCALL sqlite3_initialize(void);
1654 SQLITE_API int SQLITE_STDCALL sqlite3_shutdown(void);
1655 SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void);
1656 SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void);
1657 
1658 /*
1659 ** CAPI3REF: Configuring The SQLite Library
1660 **
1661 ** The sqlite3_config() interface is used to make global configuration
1662 ** changes to SQLite in order to tune SQLite to the specific needs of
1663 ** the application. The default configuration is recommended for most
1664 ** applications and so this routine is usually not necessary. It is
1665 ** provided to support rare applications with unusual needs.
1666 **
1667 ** <b>The sqlite3_config() interface is not threadsafe. The application
1668 ** must ensure that no other SQLite interfaces are invoked by other
1669 ** threads while sqlite3_config() is running.</b>
1670 **
1671 ** The sqlite3_config() interface
1672 ** may only be invoked prior to library initialization using
1673 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1674 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1675 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1676 ** Note, however, that ^sqlite3_config() can be called as part of the
1677 ** implementation of an application-defined [sqlite3_os_init()].
1678 **
1679 ** The first argument to sqlite3_config() is an integer
1680 ** [configuration option] that determines
1681 ** what property of SQLite is to be configured. Subsequent arguments
1682 ** vary depending on the [configuration option]
1683 ** in the first argument.
1684 **
1685 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1686 ** ^If the option is unknown or SQLite is unable to set the option
1687 ** then this routine returns a non-zero [error code].
1688 */
1689 SQLITE_API int SQLITE_CDECL sqlite3_config(int, ...);
1690 
1691 /*
1692 ** CAPI3REF: Configure database connections
1693 ** METHOD: sqlite3
1694 **
1695 ** The sqlite3_db_config() interface is used to make configuration
1696 ** changes to a [database connection]. The interface is similar to
1697 ** [sqlite3_config()] except that the changes apply to a single
1698 ** [database connection] (specified in the first argument).
1699 **
1700 ** The second argument to sqlite3_db_config(D,V,...) is the
1701 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
1702 ** that indicates what aspect of the [database connection] is being configured.
1703 ** Subsequent arguments vary depending on the configuration verb.
1704 **
1705 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1706 ** the call is considered successful.
1707 */
1708 SQLITE_API int SQLITE_CDECL sqlite3_db_config(sqlite3*, int op, ...);
1709 
1710 /*
1711 ** CAPI3REF: Memory Allocation Routines
1712 **
1713 ** An instance of this object defines the interface between SQLite
1714 ** and low-level memory allocation routines.
1715 **
1716 ** This object is used in only one place in the SQLite interface.
1717 ** A pointer to an instance of this object is the argument to
1718 ** [sqlite3_config()] when the configuration option is
1719 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1720 ** By creating an instance of this object
1721 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1722 ** during configuration, an application can specify an alternative
1723 ** memory allocation subsystem for SQLite to use for all of its
1724 ** dynamic memory needs.
1725 **
1726 ** Note that SQLite comes with several [built-in memory allocators]
1727 ** that are perfectly adequate for the overwhelming majority of applications
1728 ** and that this object is only useful to a tiny minority of applications
1729 ** with specialized memory allocation requirements. This object is
1730 ** also used during testing of SQLite in order to specify an alternative
1731 ** memory allocator that simulates memory out-of-memory conditions in
1732 ** order to verify that SQLite recovers gracefully from such
1733 ** conditions.
1734 **
1735 ** The xMalloc, xRealloc, and xFree methods must work like the
1736 ** malloc(), realloc() and free() functions from the standard C library.
1737 ** ^SQLite guarantees that the second argument to
1738 ** xRealloc is always a value returned by a prior call to xRoundup.
1739 **
1740 ** xSize should return the allocated size of a memory allocation
1741 ** previously obtained from xMalloc or xRealloc. The allocated size
1742 ** is always at least as big as the requested size but may be larger.
1743 **
1744 ** The xRoundup method returns what would be the allocated size of
1745 ** a memory allocation given a particular requested size. Most memory
1746 ** allocators round up memory allocations at least to the next multiple
1747 ** of 8. Some allocators round up to a larger multiple or to a power of 2.
1748 ** Every memory allocation request coming in through [sqlite3_malloc()]
1749 ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
1750 ** that causes the corresponding memory allocation to fail.
1751 **
1752 ** The xInit method initializes the memory allocator. For example,
1753 ** it might allocate any require mutexes or initialize internal data
1754 ** structures. The xShutdown method is invoked (indirectly) by
1755 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1756 ** by xInit. The pAppData pointer is used as the only parameter to
1757 ** xInit and xShutdown.
1758 **
1759 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1760 ** the xInit method, so the xInit method need not be threadsafe. The
1761 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1762 ** not need to be threadsafe either. For all other methods, SQLite
1763 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1764 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1765 ** it is by default) and so the methods are automatically serialized.
1766 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1767 ** methods must be threadsafe or else make their own arrangements for
1768 ** serialization.
1769 **
1770 ** SQLite will never invoke xInit() more than once without an intervening
1771 ** call to xShutdown().
1772 */
1773 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1774 struct sqlite3_mem_methods {
1775  void *(*xMalloc)(int); /* Memory allocation function */
1776  void (*xFree)(void*); /* Free a prior allocation */
1777  void *(*xRealloc)(void*,int); /* Resize an allocation */
1778  int (*xSize)(void*); /* Return the size of an allocation */
1779  int (*xRoundup)(int); /* Round up request size to allocation size */
1780  int (*xInit)(void*); /* Initialize the memory allocator */
1781  void (*xShutdown)(void*); /* Deinitialize the memory allocator */
1782  void *pAppData; /* Argument to xInit() and xShutdown() */
1783 };
1784 
1785 /*
1786 ** CAPI3REF: Configuration Options
1787 ** KEYWORDS: {configuration option}
1788 **
1789 ** These constants are the available integer configuration options that
1790 ** can be passed as the first argument to the [sqlite3_config()] interface.
1791 **
1792 ** New configuration options may be added in future releases of SQLite.
1793 ** Existing configuration options might be discontinued. Applications
1794 ** should check the return code from [sqlite3_config()] to make sure that
1795 ** the call worked. The [sqlite3_config()] interface will return a
1796 ** non-zero [error code] if a discontinued or unsupported configuration option
1797 ** is invoked.
1798 **
1799 ** <dl>
1800 ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1801 ** <dd>There are no arguments to this option. ^This option sets the
1802 ** [threading mode] to Single-thread. In other words, it disables
1803 ** all mutexing and puts SQLite into a mode where it can only be used
1804 ** by a single thread. ^If SQLite is compiled with
1805 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1806 ** it is not possible to change the [threading mode] from its default
1807 ** value of Single-thread and so [sqlite3_config()] will return
1808 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1809 ** configuration option.</dd>
1810 **
1811 ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1812 ** <dd>There are no arguments to this option. ^This option sets the
1813 ** [threading mode] to Multi-thread. In other words, it disables
1814 ** mutexing on [database connection] and [prepared statement] objects.
1815 ** The application is responsible for serializing access to
1816 ** [database connections] and [prepared statements]. But other mutexes
1817 ** are enabled so that SQLite will be safe to use in a multi-threaded
1818 ** environment as long as no two threads attempt to use the same
1819 ** [database connection] at the same time. ^If SQLite is compiled with
1820 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1821 ** it is not possible to set the Multi-thread [threading mode] and
1822 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1823 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1824 **
1825 ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
1826 ** <dd>There are no arguments to this option. ^This option sets the
1827 ** [threading mode] to Serialized. In other words, this option enables
1828 ** all mutexes including the recursive
1829 ** mutexes on [database connection] and [prepared statement] objects.
1830 ** In this mode (which is the default when SQLite is compiled with
1831 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1832 ** to [database connections] and [prepared statements] so that the
1833 ** application is free to use the same [database connection] or the
1834 ** same [prepared statement] in different threads at the same time.
1835 ** ^If SQLite is compiled with
1836 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1837 ** it is not possible to set the Serialized [threading mode] and
1838 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1839 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1840 **
1841 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
1842 ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
1843 ** a pointer to an instance of the [sqlite3_mem_methods] structure.
1844 ** The argument specifies
1845 ** alternative low-level memory allocation routines to be used in place of
1846 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1847 ** its own private copy of the content of the [sqlite3_mem_methods] structure
1848 ** before the [sqlite3_config()] call returns.</dd>
1849 **
1850 ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
1851 ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
1852 ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
1853 ** The [sqlite3_mem_methods]
1854 ** structure is filled with the currently defined memory allocation routines.)^
1855 ** This option can be used to overload the default memory allocation
1856 ** routines with a wrapper that simulations memory allocation failure or
1857 ** tracks memory usage, for example. </dd>
1858 **
1859 ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1860 ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
1861 ** interpreted as a boolean, which enables or disables the collection of
1862 ** memory allocation statistics. ^(When memory allocation statistics are
1863 ** disabled, the following SQLite interfaces become non-operational:
1864 ** <ul>
1865 ** <li> [sqlite3_memory_used()]
1866 ** <li> [sqlite3_memory_highwater()]
1867 ** <li> [sqlite3_soft_heap_limit64()]
1868 ** <li> [sqlite3_status64()]
1869 ** </ul>)^
1870 ** ^Memory allocation statistics are enabled by default unless SQLite is
1871 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1872 ** allocation statistics are disabled by default.
1873 ** </dd>
1874 **
1875 ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
1876 ** <dd> ^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer
1877 ** that SQLite can use for scratch memory. ^(There are three arguments
1878 ** to SQLITE_CONFIG_SCRATCH: A pointer an 8-byte
1879 ** aligned memory buffer from which the scratch allocations will be
1880 ** drawn, the size of each scratch allocation (sz),
1881 ** and the maximum number of scratch allocations (N).)^
1882 ** The first argument must be a pointer to an 8-byte aligned buffer
1883 ** of at least sz*N bytes of memory.
1884 ** ^SQLite will not use more than one scratch buffers per thread.
1885 ** ^SQLite will never request a scratch buffer that is more than 6
1886 ** times the database page size.
1887 ** ^If SQLite needs needs additional
1888 ** scratch memory beyond what is provided by this configuration option, then
1889 ** [sqlite3_malloc()] will be used to obtain the memory needed.<p>
1890 ** ^When the application provides any amount of scratch memory using
1891 ** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large
1892 ** [sqlite3_malloc|heap allocations].
1893 ** This can help [Robson proof|prevent memory allocation failures] due to heap
1894 ** fragmentation in low-memory embedded systems.
1895 ** </dd>
1896 **
1897 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
1898 ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
1899 ** that SQLite can use for the database page cache with the default page
1900 ** cache implementation.
1901 ** This configuration option is a no-op if an application-define page
1902 ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
1903 ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
1904 ** 8-byte aligned memory (pMem), the size of each page cache line (sz),
1905 ** and the number of cache lines (N).
1906 ** The sz argument should be the size of the largest database page
1907 ** (a power of two between 512 and 65536) plus some extra bytes for each
1908 ** page header. ^The number of extra bytes needed by the page header
1909 ** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
1910 ** ^It is harmless, apart from the wasted memory,
1911 ** for the sz parameter to be larger than necessary. The pMem
1912 ** argument must be either a NULL pointer or a pointer to an 8-byte
1913 ** aligned block of memory of at least sz*N bytes, otherwise
1914 ** subsequent behavior is undefined.
1915 ** ^When pMem is not NULL, SQLite will strive to use the memory provided
1916 ** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
1917 ** a page cache line is larger than sz bytes or if all of the pMem buffer
1918 ** is exhausted.
1919 ** ^If pMem is NULL and N is non-zero, then each database connection
1920 ** does an initial bulk allocation for page cache memory
1921 ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
1922 ** of -1024*N bytes if N is negative, . ^If additional
1923 ** page cache memory is needed beyond what is provided by the initial
1924 ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
1925 ** additional cache line. </dd>
1926 **
1927 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
1928 ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
1929 ** that SQLite will use for all of its dynamic memory allocation needs
1930 ** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and
1931 ** [SQLITE_CONFIG_PAGECACHE].
1932 ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
1933 ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
1934 ** [SQLITE_ERROR] if invoked otherwise.
1935 ** ^There are three arguments to SQLITE_CONFIG_HEAP:
1936 ** An 8-byte aligned pointer to the memory,
1937 ** the number of bytes in the memory buffer, and the minimum allocation size.
1938 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1939 ** to using its default memory allocator (the system malloc() implementation),
1940 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
1941 ** memory pointer is not NULL then the alternative memory
1942 ** allocator is engaged to handle all of SQLites memory allocation needs.
1943 ** The first pointer (the memory pointer) must be aligned to an 8-byte
1944 ** boundary or subsequent behavior of SQLite will be undefined.
1945 ** The minimum allocation size is capped at 2**12. Reasonable values
1946 ** for the minimum allocation size are 2**5 through 2**8.</dd>
1947 **
1948 ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
1949 ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
1950 ** pointer to an instance of the [sqlite3_mutex_methods] structure.
1951 ** The argument specifies alternative low-level mutex routines to be used
1952 ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of
1953 ** the content of the [sqlite3_mutex_methods] structure before the call to
1954 ** [sqlite3_config()] returns. ^If SQLite is compiled with
1955 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1956 ** the entire mutexing subsystem is omitted from the build and hence calls to
1957 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1958 ** return [SQLITE_ERROR].</dd>
1959 **
1960 ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
1961 ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
1962 ** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The
1963 ** [sqlite3_mutex_methods]
1964 ** structure is filled with the currently defined mutex routines.)^
1965 ** This option can be used to overload the default mutex allocation
1966 ** routines with a wrapper used to track mutex usage for performance
1967 ** profiling or testing, for example. ^If SQLite is compiled with
1968 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1969 ** the entire mutexing subsystem is omitted from the build and hence calls to
1970 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1971 ** return [SQLITE_ERROR].</dd>
1972 **
1973 ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1974 ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
1975 ** the default size of lookaside memory on each [database connection].
1976 ** The first argument is the
1977 ** size of each lookaside buffer slot and the second is the number of
1978 ** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE
1979 ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1980 ** option to [sqlite3_db_config()] can be used to change the lookaside
1981 ** configuration on individual connections.)^ </dd>
1982 **
1983 ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
1984 ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
1985 ** a pointer to an [sqlite3_pcache_methods2] object. This object specifies
1986 ** the interface to a custom page cache implementation.)^
1987 ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
1988 **
1989 ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
1990 ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
1991 ** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of
1992 ** the current page cache implementation into that object.)^ </dd>
1993 **
1994 ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
1995 ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
1996 ** global [error log].
1997 ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
1998 ** function with a call signature of void(*)(void*,int,const char*),
1999 ** and a pointer to void. ^If the function pointer is not NULL, it is
2000 ** invoked by [sqlite3_log()] to process each logging event. ^If the
2001 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
2002 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
2003 ** passed through as the first parameter to the application-defined logger
2004 ** function whenever that function is invoked. ^The second parameter to
2005 ** the logger function is a copy of the first parameter to the corresponding
2006 ** [sqlite3_log()] call and is intended to be a [result code] or an
2007 ** [extended result code]. ^The third parameter passed to the logger is
2008 ** log message after formatting via [sqlite3_snprintf()].
2009 ** The SQLite logging interface is not reentrant; the logger function
2010 ** supplied by the application must not invoke any SQLite interface.
2011 ** In a multi-threaded application, the application-defined logger
2012 ** function must be threadsafe. </dd>
2013 **
2014 ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
2015 ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
2016 ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
2017 ** then URI handling is globally disabled.)^ ^If URI handling is globally
2018 ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
2019 ** [sqlite3_open16()] or
2020 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
2021 ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
2022 ** connection is opened. ^If it is globally disabled, filenames are
2023 ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
2024 ** database connection is opened. ^(By default, URI handling is globally
2025 ** disabled. The default value may be changed by compiling with the
2026 ** [SQLITE_USE_URI] symbol defined.)^
2027 **
2028 ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
2029 ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
2030 ** argument which is interpreted as a boolean in order to enable or disable
2031 ** the use of covering indices for full table scans in the query optimizer.
2032 ** ^The default setting is determined
2033 ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
2034 ** if that compile-time option is omitted.
2035 ** The ability to disable the use of covering indices for full table scans
2036 ** is because some incorrectly coded legacy applications might malfunction
2037 ** when the optimization is enabled. Providing the ability to
2038 ** disable the optimization allows the older, buggy application code to work
2039 ** without change even with newer versions of SQLite.
2040 **
2041 ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
2042 ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
2043 ** <dd> These options are obsolete and should not be used by new code.
2044 ** They are retained for backwards compatibility but are now no-ops.
2045 ** </dd>
2046 **
2047 ** [[SQLITE_CONFIG_SQLLOG]]
2048 ** <dt>SQLITE_CONFIG_SQLLOG
2049 ** <dd>This option is only available if sqlite is compiled with the
2050 ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
2051 ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
2052 ** The second should be of type (void*). The callback is invoked by the library
2053 ** in three separate circumstances, identified by the value passed as the
2054 ** fourth parameter. If the fourth parameter is 0, then the database connection
2055 ** passed as the second argument has just been opened. The third argument
2056 ** points to a buffer containing the name of the main database file. If the
2057 ** fourth parameter is 1, then the SQL statement that the third parameter
2058 ** points to has just been executed. Or, if the fourth parameter is 2, then
2059 ** the connection being passed as the second parameter is being closed. The
2060 ** third parameter is passed NULL In this case. An example of using this
2061 ** configuration option can be seen in the "test_sqllog.c" source file in
2062 ** the canonical SQLite source tree.</dd>
2063 **
2064 ** [[SQLITE_CONFIG_MMAP_SIZE]]
2065 ** <dt>SQLITE_CONFIG_MMAP_SIZE
2066 ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
2067 ** that are the default mmap size limit (the default setting for
2068 ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
2069 ** ^The default setting can be overridden by each database connection using
2070 ** either the [PRAGMA mmap_size] command, or by using the
2071 ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
2072 ** will be silently truncated if necessary so that it does not exceed the
2073 ** compile-time maximum mmap size set by the
2074 ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
2075 ** ^If either argument to this option is negative, then that argument is
2076 ** changed to its compile-time default.
2077 **
2078 ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
2079 ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
2080 ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
2081 ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
2082 ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
2083 ** that specifies the maximum size of the created heap.
2084 **
2085 ** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
2086 ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
2087 ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
2088 ** is a pointer to an integer and writes into that integer the number of extra
2089 ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
2090 ** The amount of extra space required can change depending on the compiler,
2091 ** target platform, and SQLite version.
2092 **
2093 ** [[SQLITE_CONFIG_PMASZ]]
2094 ** <dt>SQLITE_CONFIG_PMASZ
2095 ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
2096 ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
2097 ** sorter to that integer. The default minimum PMA Size is set by the
2098 ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
2099 ** to help with sort operations when multithreaded sorting
2100 ** is enabled (using the [PRAGMA threads] command) and the amount of content
2101 ** to be sorted exceeds the page size times the minimum of the
2102 ** [PRAGMA cache_size] setting and this value.
2103 **
2104 ** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
2105 ** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
2106 ** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
2107 ** becomes the [statement journal] spill-to-disk threshold.
2108 ** [Statement journals] are held in memory until their size (in bytes)
2109 ** exceeds this threshold, at which point they are written to disk.
2110 ** Or if the threshold is -1, statement journals are always held
2111 ** exclusively in memory.
2112 ** Since many statement journals never become large, setting the spill
2113 ** threshold to a value such as 64KiB can greatly reduce the amount of
2114 ** I/O required to support statement rollback.
2115 ** The default value for this setting is controlled by the
2116 ** [SQLITE_STMTJRNL_SPILL] compile-time option.
2117 ** </dl>
2118 */
2119 #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
2120 #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
2121 #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
2122 #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
2123 #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
2124 #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
2125 #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
2126 #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
2127 #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
2128 #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
2129 #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
2130 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
2131 #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
2132 #define SQLITE_CONFIG_PCACHE 14 /* no-op */
2133 #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
2134 #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
2135 #define SQLITE_CONFIG_URI 17 /* int */
2136 #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
2137 #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
2138 #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
2139 #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
2140 #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
2141 #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
2142 #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */
2143 #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */
2144 #define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */
2145 
2146 /*
2147 ** CAPI3REF: Database Connection Configuration Options
2148 **
2149 ** These constants are the available integer configuration options that
2150 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
2151 **
2152 ** New configuration options may be added in future releases of SQLite.
2153 ** Existing configuration options might be discontinued. Applications
2154 ** should check the return code from [sqlite3_db_config()] to make sure that
2155 ** the call worked. ^The [sqlite3_db_config()] interface will return a
2156 ** non-zero [error code] if a discontinued or unsupported configuration option
2157 ** is invoked.
2158 **
2159 ** <dl>
2160 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2161 ** <dd> ^This option takes three additional arguments that determine the
2162 ** [lookaside memory allocator] configuration for the [database connection].
2163 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2164 ** pointer to a memory buffer to use for lookaside memory.
2165 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2166 ** may be NULL in which case SQLite will allocate the
2167 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2168 ** size of each lookaside buffer slot. ^The third argument is the number of
2169 ** slots. The size of the buffer in the first argument must be greater than
2170 ** or equal to the product of the second and third arguments. The buffer
2171 ** must be aligned to an 8-byte boundary. ^If the second argument to
2172 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2173 ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
2174 ** configuration for a database connection can only be changed when that
2175 ** connection is not currently using lookaside memory, or in other words
2176 ** when the "current value" returned by
2177 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2178 ** Any attempt to change the lookaside memory configuration when lookaside
2179 ** memory is in use leaves the configuration unchanged and returns
2180 ** [SQLITE_BUSY].)^</dd>
2181 **
2182 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2183 ** <dd> ^This option is used to enable or disable the enforcement of
2184 ** [foreign key constraints]. There should be two additional arguments.
2185 ** The first argument is an integer which is 0 to disable FK enforcement,
2186 ** positive to enable FK enforcement or negative to leave FK enforcement
2187 ** unchanged. The second parameter is a pointer to an integer into which
2188 ** is written 0 or 1 to indicate whether FK enforcement is off or on
2189 ** following this call. The second parameter may be a NULL pointer, in
2190 ** which case the FK enforcement setting is not reported back. </dd>
2191 **
2192 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2193 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2194 ** There should be two additional arguments.
2195 ** The first argument is an integer which is 0 to disable triggers,
2196 ** positive to enable triggers or negative to leave the setting unchanged.
2197 ** The second parameter is a pointer to an integer into which
2198 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
2199 ** following this call. The second parameter may be a NULL pointer, in
2200 ** which case the trigger setting is not reported back. </dd>
2201 **
2202 ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
2203 ** <dd> ^This option is used to enable or disable the two-argument
2204 ** version of the [fts3_tokenizer()] function which is part of the
2205 ** [FTS3] full-text search engine extension.
2206 ** There should be two additional arguments.
2207 ** The first argument is an integer which is 0 to disable fts3_tokenizer() or
2208 ** positive to enable fts3_tokenizer() or negative to leave the setting
2209 ** unchanged.
2210 ** The second parameter is a pointer to an integer into which
2211 ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
2212 ** following this call. The second parameter may be a NULL pointer, in
2213 ** which case the new setting is not reported back. </dd>
2214 **
2215 ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
2216 ** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
2217 ** interface independently of the [load_extension()] SQL function.
2218 ** The [sqlite3_enable_load_extension()] API enables or disables both the
2219 ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
2220 ** There should be two additional arguments.
2221 ** When the first argument to this interface is 1, then only the C-API is
2222 ** enabled and the SQL function remains disabled. If the first argument to
2223 ** this interface is 0, then both the C-API and the SQL function are disabled.
2224 ** If the first argument is -1, then no changes are made to state of either the
2225 ** C-API or the SQL function.
2226 ** The second parameter is a pointer to an integer into which
2227 ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
2228 ** is disabled or enabled following this call. The second parameter may
2229 ** be a NULL pointer, in which case the new setting is not reported back.
2230 ** </dd>
2231 **
2232 ** </dl>
2233 */
2234 #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
2235 #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
2236 #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
2237 #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
2238 #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
2239 
2240 
2241 /*
2242 ** CAPI3REF: Enable Or Disable Extended Result Codes
2243 ** METHOD: sqlite3
2244 **
2245 ** ^The sqlite3_extended_result_codes() routine enables or disables the
2246 ** [extended result codes] feature of SQLite. ^The extended result
2247 ** codes are disabled by default for historical compatibility.
2248 */
2249 SQLITE_API int SQLITE_STDCALL sqlite3_extended_result_codes(sqlite3*, int onoff);
2250 
2251 /*
2252 ** CAPI3REF: Last Insert Rowid
2253 ** METHOD: sqlite3
2254 **
2255 ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
2256 ** has a unique 64-bit signed
2257 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2258 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2259 ** names are not also used by explicitly declared columns. ^If
2260 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
2261 ** is another alias for the rowid.
2262 **
2263 ** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the
2264 ** most recent successful [INSERT] into a rowid table or [virtual table]
2265 ** on database connection D.
2266 ** ^Inserts into [WITHOUT ROWID] tables are not recorded.
2267 ** ^If no successful [INSERT]s into rowid tables
2268 ** have ever occurred on the database connection D,
2269 ** then sqlite3_last_insert_rowid(D) returns zero.
2270 **
2271 ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
2272 ** method, then this routine will return the [rowid] of the inserted
2273 ** row as long as the trigger or virtual table method is running.
2274 ** But once the trigger or virtual table method ends, the value returned
2275 ** by this routine reverts to what it was before the trigger or virtual
2276 ** table method began.)^
2277 **
2278 ** ^An [INSERT] that fails due to a constraint violation is not a
2279 ** successful [INSERT] and does not change the value returned by this
2280 ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2281 ** and INSERT OR ABORT make no changes to the return value of this
2282 ** routine when their insertion fails. ^(When INSERT OR REPLACE
2283 ** encounters a constraint violation, it does not fail. The
2284 ** INSERT continues to completion after deleting rows that caused
2285 ** the constraint problem so INSERT OR REPLACE will always change
2286 ** the return value of this interface.)^
2287 **
2288 ** ^For the purposes of this routine, an [INSERT] is considered to
2289 ** be successful even if it is subsequently rolled back.
2290 **
2291 ** This function is accessible to SQL statements via the
2292 ** [last_insert_rowid() SQL function].
2293 **
2294 ** If a separate thread performs a new [INSERT] on the same
2295 ** database connection while the [sqlite3_last_insert_rowid()]
2296 ** function is running and thus changes the last insert [rowid],
2297 ** then the value returned by [sqlite3_last_insert_rowid()] is
2298 ** unpredictable and might not equal either the old or the new
2299 ** last insert [rowid].
2300 */
2301 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_last_insert_rowid(sqlite3*);
2302 
2303 /*
2304 ** CAPI3REF: Count The Number Of Rows Modified
2305 ** METHOD: sqlite3
2306 **
2307 ** ^This function returns the number of rows modified, inserted or
2308 ** deleted by the most recently completed INSERT, UPDATE or DELETE
2309 ** statement on the database connection specified by the only parameter.
2310 ** ^Executing any other type of SQL statement does not modify the value
2311 ** returned by this function.
2312 **
2313 ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
2314 ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
2315 ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
2316 **
2317 ** Changes to a view that are intercepted by
2318 ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
2319 ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
2320 ** DELETE statement run on a view is always zero. Only changes made to real
2321 ** tables are counted.
2322 **
2323 ** Things are more complicated if the sqlite3_changes() function is
2324 ** executed while a trigger program is running. This may happen if the
2325 ** program uses the [changes() SQL function], or if some other callback
2326 ** function invokes sqlite3_changes() directly. Essentially:
2327 **
2328 ** <ul>
2329 ** <li> ^(Before entering a trigger program the value returned by
2330 ** sqlite3_changes() function is saved. After the trigger program
2331 ** has finished, the original value is restored.)^
2332 **
2333 ** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
2334 ** statement sets the value returned by sqlite3_changes()
2335 ** upon completion as normal. Of course, this value will not include
2336 ** any changes performed by sub-triggers, as the sqlite3_changes()
2337 ** value will be saved and restored after each sub-trigger has run.)^
2338 ** </ul>
2339 **
2340 ** ^This means that if the changes() SQL function (or similar) is used
2341 ** by the first INSERT, UPDATE or DELETE statement within a trigger, it
2342 ** returns the value as set when the calling statement began executing.
2343 ** ^If it is used by the second or subsequent such statement within a trigger
2344 ** program, the value returned reflects the number of rows modified by the
2345 ** previous INSERT, UPDATE or DELETE statement within the same trigger.
2346 **
2347 ** See also the [sqlite3_total_changes()] interface, the
2348 ** [count_changes pragma], and the [changes() SQL function].
2349 **
2350 ** If a separate thread makes changes on the same database connection
2351 ** while [sqlite3_changes()] is running then the value returned
2352 ** is unpredictable and not meaningful.
2353 */
2354 SQLITE_API int SQLITE_STDCALL sqlite3_changes(sqlite3*);
2355 
2356 /*
2357 ** CAPI3REF: Total Number Of Rows Modified
2358 ** METHOD: sqlite3
2359 **
2360 ** ^This function returns the total number of rows inserted, modified or
2361 ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
2362 ** since the database connection was opened, including those executed as
2363 ** part of trigger programs. ^Executing any other type of SQL statement
2364 ** does not affect the value returned by sqlite3_total_changes().
2365 **
2366 ** ^Changes made as part of [foreign key actions] are included in the
2367 ** count, but those made as part of REPLACE constraint resolution are
2368 ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
2369 ** are not counted.
2370 **
2371 ** See also the [sqlite3_changes()] interface, the
2372 ** [count_changes pragma], and the [total_changes() SQL function].
2373 **
2374 ** If a separate thread makes changes on the same database connection
2375 ** while [sqlite3_total_changes()] is running then the value
2376 ** returned is unpredictable and not meaningful.
2377 */
2378 SQLITE_API int SQLITE_STDCALL sqlite3_total_changes(sqlite3*);
2379 
2380 /*
2381 ** CAPI3REF: Interrupt A Long-Running Query
2382 ** METHOD: sqlite3
2383 **
2384 ** ^This function causes any pending database operation to abort and
2385 ** return at its earliest opportunity. This routine is typically
2386 ** called in response to a user action such as pressing "Cancel"
2387 ** or Ctrl-C where the user wants a long query operation to halt
2388 ** immediately.
2389 **
2390 ** ^It is safe to call this routine from a thread different from the
2391 ** thread that is currently running the database operation. But it
2392 ** is not safe to call this routine with a [database connection] that
2393 ** is closed or might close before sqlite3_interrupt() returns.
2394 **
2395 ** ^If an SQL operation is very nearly finished at the time when
2396 ** sqlite3_interrupt() is called, then it might not have an opportunity
2397 ** to be interrupted and might continue to completion.
2398 **
2399 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2400 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2401 ** that is inside an explicit transaction, then the entire transaction
2402 ** will be rolled back automatically.
2403 **
2404 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2405 ** SQL statements on [database connection] D complete. ^Any new SQL statements
2406 ** that are started after the sqlite3_interrupt() call and before the
2407 ** running statements reaches zero are interrupted as if they had been
2408 ** running prior to the sqlite3_interrupt() call. ^New SQL statements
2409 ** that are started after the running statement count reaches zero are
2410 ** not effected by the sqlite3_interrupt().
2411 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2412 ** SQL statements is a no-op and has no effect on SQL statements
2413 ** that are started after the sqlite3_interrupt() call returns.
2414 **
2415 ** If the database connection closes while [sqlite3_interrupt()]
2416 ** is running then bad things will likely happen.
2417 */
2418 SQLITE_API void SQLITE_STDCALL sqlite3_interrupt(sqlite3*);
2419 
2420 /*
2421 ** CAPI3REF: Determine If An SQL Statement Is Complete
2422 **
2423 ** These routines are useful during command-line input to determine if the
2424 ** currently entered text seems to form a complete SQL statement or
2425 ** if additional input is needed before sending the text into
2426 ** SQLite for parsing. ^These routines return 1 if the input string
2427 ** appears to be a complete SQL statement. ^A statement is judged to be
2428 ** complete if it ends with a semicolon token and is not a prefix of a
2429 ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
2430 ** string literals or quoted identifier names or comments are not
2431 ** independent tokens (they are part of the token in which they are
2432 ** embedded) and thus do not count as a statement terminator. ^Whitespace
2433 ** and comments that follow the final semicolon are ignored.
2434 **
2435 ** ^These routines return 0 if the statement is incomplete. ^If a
2436 ** memory allocation fails, then SQLITE_NOMEM is returned.
2437 **
2438 ** ^These routines do not parse the SQL statements thus
2439 ** will not detect syntactically incorrect SQL.
2440 **
2441 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2442 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2443 ** automatically by sqlite3_complete16(). If that initialization fails,
2444 ** then the return value from sqlite3_complete16() will be non-zero
2445 ** regardless of whether or not the input SQL is complete.)^
2446 **
2447 ** The input to [sqlite3_complete()] must be a zero-terminated
2448 ** UTF-8 string.
2449 **
2450 ** The input to [sqlite3_complete16()] must be a zero-terminated
2451 ** UTF-16 string in native byte order.
2452 */
2453 SQLITE_API int SQLITE_STDCALL sqlite3_complete(const char *sql);
2454 SQLITE_API int SQLITE_STDCALL sqlite3_complete16(const void *sql);
2455 
2456 /*
2457 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2458 ** KEYWORDS: {busy-handler callback} {busy handler}
2459 ** METHOD: sqlite3
2460 **
2461 ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
2462 ** that might be invoked with argument P whenever
2463 ** an attempt is made to access a database table associated with
2464 ** [database connection] D when another thread
2465 ** or process has the table locked.
2466 ** The sqlite3_busy_handler() interface is used to implement
2467 ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
2468 **
2469 ** ^If the busy callback is NULL, then [SQLITE_BUSY]
2470 ** is returned immediately upon encountering the lock. ^If the busy callback
2471 ** is not NULL, then the callback might be invoked with two arguments.
2472 **
2473 ** ^The first argument to the busy handler is a copy of the void* pointer which
2474 ** is the third argument to sqlite3_busy_handler(). ^The second argument to
2475 ** the busy handler callback is the number of times that the busy handler has
2476 ** been invoked previously for the same locking event. ^If the
2477 ** busy callback returns 0, then no additional attempts are made to
2478 ** access the database and [SQLITE_BUSY] is returned
2479 ** to the application.
2480 ** ^If the callback returns non-zero, then another attempt
2481 ** is made to access the database and the cycle repeats.
2482 **
2483 ** The presence of a busy handler does not guarantee that it will be invoked
2484 ** when there is lock contention. ^If SQLite determines that invoking the busy
2485 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2486 ** to the application instead of invoking the
2487 ** busy handler.
2488 ** Consider a scenario where one process is holding a read lock that
2489 ** it is trying to promote to a reserved lock and
2490 ** a second process is holding a reserved lock that it is trying
2491 ** to promote to an exclusive lock. The first process cannot proceed
2492 ** because it is blocked by the second and the second process cannot
2493 ** proceed because it is blocked by the first. If both processes
2494 ** invoke the busy handlers, neither will make any progress. Therefore,
2495 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2496 ** will induce the first process to release its read lock and allow
2497 ** the second process to proceed.
2498 **
2499 ** ^The default busy callback is NULL.
2500 **
2501 ** ^(There can only be a single busy handler defined for each
2502 ** [database connection]. Setting a new busy handler clears any
2503 ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
2504 ** or evaluating [PRAGMA busy_timeout=N] will change the
2505 ** busy handler and thus clear any previously set busy handler.
2506 **
2507 ** The busy callback should not take any actions which modify the
2508 ** database connection that invoked the busy handler. In other words,
2509 ** the busy handler is not reentrant. Any such actions
2510 ** result in undefined behavior.
2511 **
2512 ** A busy handler must not close the database connection
2513 ** or [prepared statement] that invoked the busy handler.
2514 */
2515 SQLITE_API int SQLITE_STDCALL sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);
2516 
2517 /*
2518 ** CAPI3REF: Set A Busy Timeout
2519 ** METHOD: sqlite3
2520 **
2521 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2522 ** for a specified amount of time when a table is locked. ^The handler
2523 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2524 ** have accumulated. ^After at least "ms" milliseconds of sleeping,
2525 ** the handler returns 0 which causes [sqlite3_step()] to return
2526 ** [SQLITE_BUSY].
2527 **
2528 ** ^Calling this routine with an argument less than or equal to zero
2529 ** turns off all busy handlers.
2530 **
2531 ** ^(There can only be a single busy handler for a particular
2532 ** [database connection] at any given moment. If another busy handler
2533 ** was defined (using [sqlite3_busy_handler()]) prior to calling
2534 ** this routine, that other busy handler is cleared.)^
2535 **
2536 ** See also: [PRAGMA busy_timeout]
2537 */
2538 SQLITE_API int SQLITE_STDCALL sqlite3_busy_timeout(sqlite3*, int ms);
2539 
2540 /*
2541 ** CAPI3REF: Convenience Routines For Running Queries
2542 ** METHOD: sqlite3
2543 **
2544 ** This is a legacy interface that is preserved for backwards compatibility.
2545 ** Use of this interface is not recommended.
2546 **
2547 ** Definition: A <b>result table</b> is memory data structure created by the
2548 ** [sqlite3_get_table()] interface. A result table records the
2549 ** complete query results from one or more queries.
2550 **
2551 ** The table conceptually has a number of rows and columns. But
2552 ** these numbers are not part of the result table itself. These
2553 ** numbers are obtained separately. Let N be the number of rows
2554 ** and M be the number of columns.
2555 **
2556 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2557 ** There are (N+1)*M elements in the array. The first M pointers point
2558 ** to zero-terminated strings that contain the names of the columns.
2559 ** The remaining entries all point to query results. NULL values result
2560 ** in NULL pointers. All other values are in their UTF-8 zero-terminated
2561 ** string representation as returned by [sqlite3_column_text()].
2562 **
2563 ** A result table might consist of one or more memory allocations.
2564 ** It is not safe to pass a result table directly to [sqlite3_free()].
2565 ** A result table should be deallocated using [sqlite3_free_table()].
2566 **
2567 ** ^(As an example of the result table format, suppose a query result
2568 ** is as follows:
2569 **
2570 ** <blockquote><pre>
2571 ** Name | Age
2572 ** -----------------------
2573 ** Alice | 43
2574 ** Bob | 28
2575 ** Cindy | 21
2576 ** </pre></blockquote>
2577 **
2578 ** There are two column (M==2) and three rows (N==3). Thus the
2579 ** result table has 8 entries. Suppose the result table is stored
2580 ** in an array names azResult. Then azResult holds this content:
2581 **
2582 ** <blockquote><pre>
2583 ** azResult&#91;0] = "Name";
2584 ** azResult&#91;1] = "Age";
2585 ** azResult&#91;2] = "Alice";
2586 ** azResult&#91;3] = "43";
2587 ** azResult&#91;4] = "Bob";
2588 ** azResult&#91;5] = "28";
2589 ** azResult&#91;6] = "Cindy";
2590 ** azResult&#91;7] = "21";
2591 ** </pre></blockquote>)^
2592 **
2593 ** ^The sqlite3_get_table() function evaluates one or more
2594 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2595 ** string of its 2nd parameter and returns a result table to the
2596 ** pointer given in its 3rd parameter.
2597 **
2598 ** After the application has finished with the result from sqlite3_get_table(),
2599 ** it must pass the result table pointer to sqlite3_free_table() in order to
2600 ** release the memory that was malloced. Because of the way the
2601 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2602 ** function must not try to call [sqlite3_free()] directly. Only
2603 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2604 **
2605 ** The sqlite3_get_table() interface is implemented as a wrapper around
2606 ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
2607 ** to any internal data structures of SQLite. It uses only the public
2608 ** interface defined here. As a consequence, errors that occur in the
2609 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2610 ** reflected in subsequent calls to [sqlite3_errcode()] or
2611 ** [sqlite3_errmsg()].
2612 */
2613 SQLITE_API int SQLITE_STDCALL sqlite3_get_table(
2614  sqlite3 *db, /* An open database */
2615  const char *zSql, /* SQL to be evaluated */
2616  char ***pazResult, /* Results of the query */
2617  int *pnRow, /* Number of result rows written here */
2618  int *pnColumn, /* Number of result columns written here */
2619  char **pzErrmsg /* Error msg written here */
2620 );
2621 SQLITE_API void SQLITE_STDCALL sqlite3_free_table(char **result);
2622 
2623 /*
2624 ** CAPI3REF: Formatted String Printing Functions
2625 **
2626 ** These routines are work-alikes of the "printf()" family of functions
2627 ** from the standard C library.
2628 ** These routines understand most of the common K&R formatting options,
2629 ** plus some additional non-standard formats, detailed below.
2630 ** Note that some of the more obscure formatting options from recent
2631 ** C-library standards are omitted from this implementation.
2632 **
2633 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2634 ** results into memory obtained from [sqlite3_malloc()].
2635 ** The strings returned by these two routines should be
2636 ** released by [sqlite3_free()]. ^Both routines return a
2637 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2638 ** memory to hold the resulting string.
2639 **
2640 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2641 ** the standard C library. The result is written into the
2642 ** buffer supplied as the second parameter whose size is given by
2643 ** the first parameter. Note that the order of the
2644 ** first two parameters is reversed from snprintf().)^ This is an
2645 ** historical accident that cannot be fixed without breaking
2646 ** backwards compatibility. ^(Note also that sqlite3_snprintf()
2647 ** returns a pointer to its buffer instead of the number of
2648 ** characters actually written into the buffer.)^ We admit that
2649 ** the number of characters written would be a more useful return
2650 ** value but we cannot change the implementation of sqlite3_snprintf()
2651 ** now without breaking compatibility.
2652 **
2653 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2654 ** guarantees that the buffer is always zero-terminated. ^The first
2655 ** parameter "n" is the total size of the buffer, including space for
2656 ** the zero terminator. So the longest string that can be completely
2657 ** written will be n-1 characters.
2658 **
2659 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2660 **
2661 ** These routines all implement some additional formatting
2662 ** options that are useful for constructing SQL statements.
2663 ** All of the usual printf() formatting options apply. In addition, there
2664 ** is are "%q", "%Q", "%w" and "%z" options.
2665 **
2666 ** ^(The %q option works like %s in that it substitutes a nul-terminated
2667 ** string from the argument list. But %q also doubles every '\'' character.
2668 ** %q is designed for use inside a string literal.)^ By doubling each '\''
2669 ** character it escapes that character and allows it to be inserted into
2670 ** the string.
2671 **
2672 ** For example, assume the string variable zText contains text as follows:
2673 **
2674 ** <blockquote><pre>
2675 ** char *zText = "It's a happy day!";
2676 ** </pre></blockquote>
2677 **
2678 ** One can use this text in an SQL statement as follows:
2679 **
2680 ** <blockquote><pre>
2681 ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2682 ** sqlite3_exec(db, zSQL, 0, 0, 0);
2683 ** sqlite3_free(zSQL);
2684 ** </pre></blockquote>
2685 **
2686 ** Because the %q format string is used, the '\'' character in zText
2687 ** is escaped and the SQL generated is as follows:
2688 **
2689 ** <blockquote><pre>
2690 ** INSERT INTO table1 VALUES('It''s a happy day!')
2691 ** </pre></blockquote>
2692 **
2693 ** This is correct. Had we used %s instead of %q, the generated SQL
2694 ** would have looked like this:
2695 **
2696 ** <blockquote><pre>
2697 ** INSERT INTO table1 VALUES('It's a happy day!');
2698 ** </pre></blockquote>
2699 **
2700 ** This second example is an SQL syntax error. As a general rule you should
2701 ** always use %q instead of %s when inserting text into a string literal.
2702 **
2703 ** ^(The %Q option works like %q except it also adds single quotes around
2704 ** the outside of the total string. Additionally, if the parameter in the
2705 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2706 ** single quotes).)^ So, for example, one could say:
2707 **
2708 ** <blockquote><pre>
2709 ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2710 ** sqlite3_exec(db, zSQL, 0, 0, 0);
2711 ** sqlite3_free(zSQL);
2712 ** </pre></blockquote>
2713 **
2714 ** The code above will render a correct SQL statement in the zSQL
2715 ** variable even if the zText variable is a NULL pointer.
2716 **
2717 ** ^(The "%w" formatting option is like "%q" except that it expects to
2718 ** be contained within double-quotes instead of single quotes, and it
2719 ** escapes the double-quote character instead of the single-quote
2720 ** character.)^ The "%w" formatting option is intended for safely inserting
2721 ** table and column names into a constructed SQL statement.
2722 **
2723 ** ^(The "%z" formatting option works like "%s" but with the
2724 ** addition that after the string has been read and copied into
2725 ** the result, [sqlite3_free()] is called on the input string.)^
2726 */
2727 SQLITE_API char *SQLITE_CDECL sqlite3_mprintf(const char*,...);
2728 SQLITE_API char *SQLITE_STDCALL sqlite3_vmprintf(const char*, va_list);
2729 SQLITE_API char *SQLITE_CDECL sqlite3_snprintf(int,char*,const char*, ...);
2730 SQLITE_API char *SQLITE_STDCALL sqlite3_vsnprintf(int,char*,const char*, va_list);
2731 
2732 /*
2733 ** CAPI3REF: Memory Allocation Subsystem
2734 **
2735 ** The SQLite core uses these three routines for all of its own
2736 ** internal memory allocation needs. "Core" in the previous sentence
2737 ** does not include operating-system specific VFS implementation. The
2738 ** Windows VFS uses native malloc() and free() for some operations.
2739 **
2740 ** ^The sqlite3_malloc() routine returns a pointer to a block
2741 ** of memory at least N bytes in length, where N is the parameter.
2742 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2743 ** memory, it returns a NULL pointer. ^If the parameter N to
2744 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2745 ** a NULL pointer.
2746 **
2747 ** ^The sqlite3_malloc64(N) routine works just like
2748 ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
2749 ** of a signed 32-bit integer.
2750 **
2751 ** ^Calling sqlite3_free() with a pointer previously returned
2752 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2753 ** that it might be reused. ^The sqlite3_free() routine is
2754 ** a no-op if is called with a NULL pointer. Passing a NULL pointer
2755 ** to sqlite3_free() is harmless. After being freed, memory
2756 ** should neither be read nor written. Even reading previously freed
2757 ** memory might result in a segmentation fault or other severe error.
2758 ** Memory corruption, a segmentation fault, or other severe error
2759 ** might result if sqlite3_free() is called with a non-NULL pointer that
2760 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2761 **
2762 ** ^The sqlite3_realloc(X,N) interface attempts to resize a
2763 ** prior memory allocation X to be at least N bytes.
2764 ** ^If the X parameter to sqlite3_realloc(X,N)
2765 ** is a NULL pointer then its behavior is identical to calling
2766 ** sqlite3_malloc(N).
2767 ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
2768 ** negative then the behavior is exactly the same as calling
2769 ** sqlite3_free(X).
2770 ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
2771 ** of at least N bytes in size or NULL if insufficient memory is available.
2772 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2773 ** of the prior allocation are copied into the beginning of buffer returned
2774 ** by sqlite3_realloc(X,N) and the prior allocation is freed.
2775 ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
2776 ** prior allocation is not freed.
2777 **
2778 ** ^The sqlite3_realloc64(X,N) interfaces works the same as
2779 ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
2780 ** of a 32-bit signed integer.
2781 **
2782 ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
2783 ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
2784 ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
2785 ** ^The value returned by sqlite3_msize(X) might be larger than the number
2786 ** of bytes requested when X was allocated. ^If X is a NULL pointer then
2787 ** sqlite3_msize(X) returns zero. If X points to something that is not
2788 ** the beginning of memory allocation, or if it points to a formerly
2789 ** valid memory allocation that has now been freed, then the behavior
2790 ** of sqlite3_msize(X) is undefined and possibly harmful.
2791 **
2792 ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
2793 ** sqlite3_malloc64(), and sqlite3_realloc64()
2794 ** is always aligned to at least an 8 byte boundary, or to a
2795 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2796 ** option is used.
2797 **
2798 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2799 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2800 ** implementation of these routines to be omitted. That capability
2801 ** is no longer provided. Only built-in memory allocators can be used.
2802 **
2803 ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
2804 ** the system malloc() and free() directly when converting
2805 ** filenames between the UTF-8 encoding used by SQLite
2806 ** and whatever filename encoding is used by the particular Windows
2807 ** installation. Memory allocation errors were detected, but
2808 ** they were reported back as [SQLITE_CANTOPEN] or
2809 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2810 **
2811 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2812 ** must be either NULL or else pointers obtained from a prior
2813 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2814 ** not yet been released.
2815 **
2816 ** The application must not read or write any part of
2817 ** a block of memory after it has been released using
2818 ** [sqlite3_free()] or [sqlite3_realloc()].
2819 */
2820 SQLITE_API void *SQLITE_STDCALL sqlite3_malloc(int);
2821 SQLITE_API void *SQLITE_STDCALL sqlite3_malloc64(sqlite3_uint64);
2822 SQLITE_API void *SQLITE_STDCALL sqlite3_realloc(void*, int);
2823 SQLITE_API void *SQLITE_STDCALL sqlite3_realloc64(void*, sqlite3_uint64);
2824 SQLITE_API void SQLITE_STDCALL sqlite3_free(void*);
2825 SQLITE_API sqlite3_uint64 SQLITE_STDCALL sqlite3_msize(void*);
2826 
2827 /*
2828 ** CAPI3REF: Memory Allocator Statistics
2829 **
2830 ** SQLite provides these two interfaces for reporting on the status
2831 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2832 ** routines, which form the built-in memory allocation subsystem.
2833 **
2834 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2835 ** of memory currently outstanding (malloced but not freed).
2836 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2837 ** value of [sqlite3_memory_used()] since the high-water mark
2838 ** was last reset. ^The values returned by [sqlite3_memory_used()] and
2839 ** [sqlite3_memory_highwater()] include any overhead
2840 ** added by SQLite in its implementation of [sqlite3_malloc()],
2841 ** but not overhead added by the any underlying system library
2842 ** routines that [sqlite3_malloc()] may call.
2843 **
2844 ** ^The memory high-water mark is reset to the current value of
2845 ** [sqlite3_memory_used()] if and only if the parameter to
2846 ** [sqlite3_memory_highwater()] is true. ^The value returned
2847 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2848 ** prior to the reset.
2849 */
2850 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_used(void);
2851 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_highwater(int resetFlag);
2852 
2853 /*
2854 ** CAPI3REF: Pseudo-Random Number Generator
2855 **
2856 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2857 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2858 ** already uses the largest possible [ROWID]. The PRNG is also used for
2859 ** the build-in random() and randomblob() SQL functions. This interface allows
2860 ** applications to access the same PRNG for other purposes.
2861 **
2862 ** ^A call to this routine stores N bytes of randomness into buffer P.
2863 ** ^The P parameter can be a NULL pointer.
2864 **
2865 ** ^If this routine has not been previously called or if the previous
2866 ** call had N less than one or a NULL pointer for P, then the PRNG is
2867 ** seeded using randomness obtained from the xRandomness method of
2868 ** the default [sqlite3_vfs] object.
2869 ** ^If the previous call to this routine had an N of 1 or more and a
2870 ** non-NULL P then the pseudo-randomness is generated
2871 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2872 ** method.
2873 */
2874 SQLITE_API void SQLITE_STDCALL sqlite3_randomness(int N, void *P);
2875 
2876 /*
2877 ** CAPI3REF: Compile-Time Authorization Callbacks
2878 ** METHOD: sqlite3
2879 **
2880 ** ^This routine registers an authorizer callback with a particular
2881 ** [database connection], supplied in the first argument.
2882 ** ^The authorizer callback is invoked as SQL statements are being compiled
2883 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2884 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
2885 ** points during the compilation process, as logic is being created
2886 ** to perform various actions, the authorizer callback is invoked to
2887 ** see if those actions are allowed. ^The authorizer callback should
2888 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2889 ** specific action but allow the SQL statement to continue to be
2890 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2891 ** rejected with an error. ^If the authorizer callback returns
2892 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2893 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2894 ** the authorizer will fail with an error message.
2895 **
2896 ** When the callback returns [SQLITE_OK], that means the operation
2897 ** requested is ok. ^When the callback returns [SQLITE_DENY], the
2898 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2899 ** authorizer will fail with an error message explaining that
2900 ** access is denied.
2901 **
2902 ** ^The first parameter to the authorizer callback is a copy of the third
2903 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2904 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2905 ** the particular action to be authorized. ^The third through sixth parameters
2906 ** to the callback are zero-terminated strings that contain additional
2907 ** details about the action to be authorized.
2908 **
2909 ** ^If the action code is [SQLITE_READ]
2910 ** and the callback returns [SQLITE_IGNORE] then the
2911 ** [prepared statement] statement is constructed to substitute
2912 ** a NULL value in place of the table column that would have
2913 ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
2914 ** return can be used to deny an untrusted user access to individual
2915 ** columns of a table.
2916 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2917 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2918 ** [truncate optimization] is disabled and all rows are deleted individually.
2919 **
2920 ** An authorizer is used when [sqlite3_prepare | preparing]
2921 ** SQL statements from an untrusted source, to ensure that the SQL statements
2922 ** do not try to access data they are not allowed to see, or that they do not
2923 ** try to execute malicious statements that damage the database. For
2924 ** example, an application may allow a user to enter arbitrary
2925 ** SQL queries for evaluation by a database. But the application does
2926 ** not want the user to be able to make arbitrary changes to the
2927 ** database. An authorizer could then be put in place while the
2928 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2929 ** disallows everything except [SELECT] statements.
2930 **
2931 ** Applications that need to process SQL from untrusted sources
2932 ** might also consider lowering resource limits using [sqlite3_limit()]
2933 ** and limiting database size using the [max_page_count] [PRAGMA]
2934 ** in addition to using an authorizer.
2935 **
2936 ** ^(Only a single authorizer can be in place on a database connection
2937 ** at a time. Each call to sqlite3_set_authorizer overrides the
2938 ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
2939 ** The authorizer is disabled by default.
2940 **
2941 ** The authorizer callback must not do anything that will modify
2942 ** the database connection that invoked the authorizer callback.
2943 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2944 ** database connections for the meaning of "modify" in this paragraph.
2945 **
2946 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2947 ** statement might be re-prepared during [sqlite3_step()] due to a
2948 ** schema change. Hence, the application should ensure that the
2949 ** correct authorizer callback remains in place during the [sqlite3_step()].
2950 **
2951 ** ^Note that the authorizer callback is invoked only during
2952 ** [sqlite3_prepare()] or its variants. Authorization is not
2953 ** performed during statement evaluation in [sqlite3_step()], unless
2954 ** as stated in the previous paragraph, sqlite3_step() invokes
2955 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2956 */
2957 SQLITE_API int SQLITE_STDCALL sqlite3_set_authorizer(
2958  sqlite3*,
2959  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2960  void *pUserData
2961 );
2962 
2963 /*
2964 ** CAPI3REF: Authorizer Return Codes
2965 **
2966 ** The [sqlite3_set_authorizer | authorizer callback function] must
2967 ** return either [SQLITE_OK] or one of these two constants in order
2968 ** to signal SQLite whether or not the action is permitted. See the
2969 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2970 ** information.
2971 **
2972 ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
2973 ** returned from the [sqlite3_vtab_on_conflict()] interface.
2974 */
2975 #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
2976 #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
2977 
2978 /*
2979 ** CAPI3REF: Authorizer Action Codes
2980 **
2981 ** The [sqlite3_set_authorizer()] interface registers a callback function
2982 ** that is invoked to authorize certain SQL statement actions. The
2983 ** second parameter to the callback is an integer code that specifies
2984 ** what action is being authorized. These are the integer action codes that
2985 ** the authorizer callback may be passed.
2986 **
2987 ** These action code values signify what kind of operation is to be
2988 ** authorized. The 3rd and 4th parameters to the authorization
2989 ** callback function will be parameters or NULL depending on which of these
2990 ** codes is used as the second parameter. ^(The 5th parameter to the
2991 ** authorizer callback is the name of the database ("main", "temp",
2992 ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
2993 ** is the name of the inner-most trigger or view that is responsible for
2994 ** the access attempt or NULL if this access attempt is directly from
2995 ** top-level SQL code.
2996 */
2997 /******************************************* 3rd ************ 4th ***********/
2998 #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
2999 #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
3000 #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
3001 #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
3002 #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
3003 #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
3004 #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
3005 #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
3006 #define SQLITE_DELETE 9 /* Table Name NULL */
3007 #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
3008 #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
3009 #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
3010 #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
3011 #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
3012 #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
3013 #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
3014 #define SQLITE_DROP_VIEW 17 /* View Name NULL */
3015 #define SQLITE_INSERT 18 /* Table Name NULL */
3016 #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
3017 #define SQLITE_READ 20 /* Table Name Column Name */
3018 #define SQLITE_SELECT 21 /* NULL NULL */
3019 #define SQLITE_TRANSACTION 22 /* Operation NULL */
3020 #define SQLITE_UPDATE 23 /* Table Name Column Name */
3021 #define SQLITE_ATTACH 24 /* Filename NULL */
3022 #define SQLITE_DETACH 25 /* Database Name NULL */
3023 #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
3024 #define SQLITE_REINDEX 27 /* Index Name NULL */
3025 #define SQLITE_ANALYZE 28 /* Table Name NULL */
3026 #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
3027 #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
3028 #define SQLITE_FUNCTION 31 /* NULL Function Name */
3029 #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
3030 #define SQLITE_COPY 0 /* No longer used */
3031 #define SQLITE_RECURSIVE 33 /* NULL NULL */
3032 
3033 /*
3034 ** CAPI3REF: Tracing And Profiling Functions
3035 ** METHOD: sqlite3
3036 **
3037 ** These routines are deprecated. Use the [sqlite3_trace_v2()] interface
3038 ** instead of the routines described here.
3039 **
3040 ** These routines register callback functions that can be used for
3041 ** tracing and profiling the execution of SQL statements.
3042 **
3043 ** ^The callback function registered by sqlite3_trace() is invoked at
3044 ** various times when an SQL statement is being run by [sqlite3_step()].
3045 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
3046 ** SQL statement text as the statement first begins executing.
3047 ** ^(Additional sqlite3_trace() callbacks might occur
3048 ** as each triggered subprogram is entered. The callbacks for triggers
3049 ** contain a UTF-8 SQL comment that identifies the trigger.)^
3050 **
3051 ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
3052 ** the length of [bound parameter] expansion in the output of sqlite3_trace().
3053 **
3054 ** ^The callback function registered by sqlite3_profile() is invoked
3055 ** as each SQL statement finishes. ^The profile callback contains
3056 ** the original statement text and an estimate of wall-clock time
3057 ** of how long that statement took to run. ^The profile callback
3058 ** time is in units of nanoseconds, however the current implementation
3059 ** is only capable of millisecond resolution so the six least significant
3060 ** digits in the time are meaningless. Future versions of SQLite
3061 ** might provide greater resolution on the profiler callback. The
3062 ** sqlite3_profile() function is considered experimental and is
3063 ** subject to change in future versions of SQLite.
3064 */
3065 SQLITE_API SQLITE_DEPRECATED void *SQLITE_STDCALL sqlite3_trace(sqlite3*,
3066  void(*xTrace)(void*,const char*), void*);
3067 SQLITE_API SQLITE_DEPRECATED void *SQLITE_STDCALL sqlite3_profile(sqlite3*,
3068  void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
3069 
3070 /*
3071 ** CAPI3REF: SQL Trace Event Codes
3072 ** KEYWORDS: SQLITE_TRACE
3073 **
3074 ** These constants identify classes of events that can be monitored
3075 ** using the [sqlite3_trace_v2()] tracing logic. The third argument
3076 ** to [sqlite3_trace_v2()] is an OR-ed combination of one or more of
3077 ** the following constants. ^The first argument to the trace callback
3078 ** is one of the following constants.
3079 **
3080 ** New tracing constants may be added in future releases.
3081 **
3082 ** ^A trace callback has four arguments: xCallback(T,C,P,X).
3083 ** ^The T argument is one of the integer type codes above.
3084 ** ^The C argument is a copy of the context pointer passed in as the
3085 ** fourth argument to [sqlite3_trace_v2()].
3086 ** The P and X arguments are pointers whose meanings depend on T.
3087 **
3088 ** <dl>
3089 ** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>
3090 ** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
3091 ** first begins running and possibly at other times during the
3092 ** execution of the prepared statement, such as at the start of each
3093 ** trigger subprogram. ^The P argument is a pointer to the
3094 ** [prepared statement]. ^The X argument is a pointer to a string which
3095 ** is the unexpanded SQL text of the prepared statement or an SQL comment
3096 ** that indicates the invocation of a trigger. ^The callback can compute
3097 ** the same text that would have been returned by the legacy [sqlite3_trace()]
3098 ** interface by using the X argument when X begins with "--" and invoking
3099 ** [sqlite3_expanded_sql(P)] otherwise.
3100 **
3101 ** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>
3102 ** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same
3103 ** information as is provided by the [sqlite3_profile()] callback.
3104 ** ^The P argument is a pointer to the [prepared statement] and the
3105 ** X argument points to a 64-bit integer which is the estimated of
3106 ** the number of nanosecond that the prepared statement took to run.
3107 ** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.
3108 **
3109 ** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
3110 ** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
3111 ** statement generates a single row of result.
3112 ** ^The P argument is a pointer to the [prepared statement] and the
3113 ** X argument is unused.
3114 **
3115 ** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>
3116 ** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database
3117 ** connection closes.
3118 ** ^The P argument is a pointer to the [database connection] object
3119 ** and the X argument is unused.
3120 ** </dl>
3121 */
3122 #define SQLITE_TRACE_STMT 0x01
3123 #define SQLITE_TRACE_PROFILE 0x02
3124 #define SQLITE_TRACE_ROW 0x04
3125 #define SQLITE_TRACE_CLOSE 0x08
3126 
3127 /*
3128 ** CAPI3REF: SQL Trace Hook
3129 ** METHOD: sqlite3
3130 **
3131 ** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback
3132 ** function X against [database connection] D, using property mask M
3133 ** and context pointer P. ^If the X callback is
3134 ** NULL or if the M mask is zero, then tracing is disabled. The
3135 ** M argument should be the bitwise OR-ed combination of
3136 ** zero or more [SQLITE_TRACE] constants.
3137 **
3138 ** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides
3139 ** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().
3140 **
3141 ** ^The X callback is invoked whenever any of the events identified by
3142 ** mask M occur. ^The integer return value from the callback is currently
3143 ** ignored, though this may change in future releases. Callback
3144 ** implementations should return zero to ensure future compatibility.
3145 **
3146 ** ^A trace callback is invoked with four arguments: callback(T,C,P,X).
3147 ** ^The T argument is one of the [SQLITE_TRACE]
3148 ** constants to indicate why the callback was invoked.
3149 ** ^The C argument is a copy of the context pointer.
3150 ** The P and X arguments are pointers whose meanings depend on T.
3151 **
3152 ** The sqlite3_trace_v2() interface is intended to replace the legacy
3153 ** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which
3154 ** are deprecated.
3155 */
3156 SQLITE_API int SQLITE_STDCALL sqlite3_trace_v2(
3157  sqlite3*,
3158  unsigned uMask,
3159  int(*xCallback)(unsigned,void*,void*,void*),
3160  void *pCtx
3161 );
3162 
3163 /*
3164 ** CAPI3REF: Query Progress Callbacks
3165 ** METHOD: sqlite3
3166 **
3167 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
3168 ** function X to be invoked periodically during long running calls to
3169 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
3170 ** database connection D. An example use for this
3171 ** interface is to keep a GUI updated during a large query.
3172 **
3173 ** ^The parameter P is passed through as the only parameter to the
3174 ** callback function X. ^The parameter N is the approximate number of
3175 ** [virtual machine instructions] that are evaluated between successive
3176 ** invocations of the callback X. ^If N is less than one then the progress
3177 ** handler is disabled.
3178 **
3179 ** ^Only a single progress handler may be defined at one time per
3180 ** [database connection]; setting a new progress handler cancels the
3181 ** old one. ^Setting parameter X to NULL disables the progress handler.
3182 ** ^The progress handler is also disabled by setting N to a value less
3183 ** than 1.
3184 **
3185 ** ^If the progress callback returns non-zero, the operation is
3186 ** interrupted. This feature can be used to implement a
3187 ** "Cancel" button on a GUI progress dialog box.
3188 **
3189 ** The progress handler callback must not do anything that will modify
3190 ** the database connection that invoked the progress handler.
3191 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3192 ** database connections for the meaning of "modify" in this paragraph.
3193 **
3194 */
3195 SQLITE_API void SQLITE_STDCALL sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
3196 
3197 /*
3198 ** CAPI3REF: Opening A New Database Connection
3199 ** CONSTRUCTOR: sqlite3
3200 **
3201 ** ^These routines open an SQLite database file as specified by the
3202 ** filename argument. ^The filename argument is interpreted as UTF-8 for
3203 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
3204 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
3205 ** returned in *ppDb, even if an error occurs. The only exception is that
3206 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
3207 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
3208 ** object.)^ ^(If the database is opened (and/or created) successfully, then
3209 ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
3210 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
3211 ** an English language description of the error following a failure of any
3212 ** of the sqlite3_open() routines.
3213 **
3214 ** ^The default encoding will be UTF-8 for databases created using
3215 ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
3216 ** created using sqlite3_open16() will be UTF-16 in the native byte order.
3217 **
3218 ** Whether or not an error occurs when it is opened, resources
3219 ** associated with the [database connection] handle should be released by
3220 ** passing it to [sqlite3_close()] when it is no longer required.
3221 **
3222 ** The sqlite3_open_v2() interface works like sqlite3_open()
3223 ** except that it accepts two additional parameters for additional control
3224 ** over the new database connection. ^(The flags parameter to
3225 ** sqlite3_open_v2() can take one of
3226 ** the following three values, optionally combined with the
3227 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
3228 ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
3229 **
3230 ** <dl>
3231 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
3232 ** <dd>The database is opened in read-only mode. If the database does not
3233 ** already exist, an error is returned.</dd>)^
3234 **
3235 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
3236 ** <dd>The database is opened for reading and writing if possible, or reading
3237 ** only if the file is write protected by the operating system. In either
3238 ** case the database must already exist, otherwise an error is returned.</dd>)^
3239 **
3240 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
3241 ** <dd>The database is opened for reading and writing, and is created if
3242 ** it does not already exist. This is the behavior that is always used for
3243 ** sqlite3_open() and sqlite3_open16().</dd>)^
3244 ** </dl>
3245 **
3246 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
3247 ** combinations shown above optionally combined with other
3248 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
3249 ** then the behavior is undefined.
3250 **
3251 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
3252 ** opens in the multi-thread [threading mode] as long as the single-thread
3253 ** mode has not been set at compile-time or start-time. ^If the
3254 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
3255 ** in the serialized [threading mode] unless single-thread was
3256 ** previously selected at compile-time or start-time.
3257 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
3258 ** eligible to use [shared cache mode], regardless of whether or not shared
3259 ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
3260 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
3261 ** participate in [shared cache mode] even if it is enabled.
3262 **
3263 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
3264 ** [sqlite3_vfs] object that defines the operating system interface that
3265 ** the new database connection should use. ^If the fourth parameter is
3266 ** a NULL pointer then the default [sqlite3_vfs] object is used.
3267 **
3268 ** ^If the filename is ":memory:", then a private, temporary in-memory database
3269 ** is created for the connection. ^This in-memory database will vanish when
3270 ** the database connection is closed. Future versions of SQLite might
3271 ** make use of additional special filenames that begin with the ":" character.
3272 ** It is recommended that when a database filename actually does begin with
3273 ** a ":" character you should prefix the filename with a pathname such as
3274 ** "./" to avoid ambiguity.
3275 **
3276 ** ^If the filename is an empty string, then a private, temporary
3277 ** on-disk database will be created. ^This private database will be
3278 ** automatically deleted as soon as the database connection is closed.
3279 **
3280 ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
3281 **
3282 ** ^If [URI filename] interpretation is enabled, and the filename argument
3283 ** begins with "file:", then the filename is interpreted as a URI. ^URI
3284 ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
3285 ** set in the fourth argument to sqlite3_open_v2(), or if it has
3286 ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
3287 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
3288 ** As of SQLite version 3.7.7, URI filename interpretation is turned off
3289 ** by default, but future releases of SQLite might enable URI filename
3290 ** interpretation by default. See "[URI filenames]" for additional
3291 ** information.
3292 **
3293 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
3294 ** authority, then it must be either an empty string or the string
3295 ** "localhost". ^If the authority is not an empty string or "localhost", an
3296 ** error is returned to the caller. ^The fragment component of a URI, if
3297 ** present, is ignored.
3298 **
3299 ** ^SQLite uses the path component of the URI as the name of the disk file
3300 ** which contains the database. ^If the path begins with a '/' character,
3301 ** then it is interpreted as an absolute path. ^If the path does not begin
3302 ** with a '/' (meaning that the authority section is omitted from the URI)
3303 ** then the path is interpreted as a relative path.
3304 ** ^(On windows, the first component of an absolute path
3305 ** is a drive specification (e.g. "C:").)^
3306 **
3307 ** [[core URI query parameters]]
3308 ** The query component of a URI may contain parameters that are interpreted
3309 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
3310 ** SQLite and its built-in [VFSes] interpret the
3311 ** following query parameters:
3312 **
3313 ** <ul>
3314 ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3315 ** a VFS object that provides the operating system interface that should
3316 ** be used to access the database file on disk. ^If this option is set to
3317 ** an empty string the default VFS object is used. ^Specifying an unknown
3318 ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
3319 ** present, then the VFS specified by the option takes precedence over
3320 ** the value passed as the fourth parameter to sqlite3_open_v2().
3321 **
3322 ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
3323 ** "rwc", or "memory". Attempting to set it to any other value is
3324 ** an error)^.
3325 ** ^If "ro" is specified, then the database is opened for read-only
3326 ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
3327 ** third argument to sqlite3_open_v2(). ^If the mode option is set to
3328 ** "rw", then the database is opened for read-write (but not create)
3329 ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
3330 ** been set. ^Value "rwc" is equivalent to setting both
3331 ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
3332 ** set to "memory" then a pure [in-memory database] that never reads
3333 ** or writes from disk is used. ^It is an error to specify a value for
3334 ** the mode parameter that is less restrictive than that specified by
3335 ** the flags passed in the third parameter to sqlite3_open_v2().
3336 **
3337 ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3338 ** "private". ^Setting it to "shared" is equivalent to setting the
3339 ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
3340 ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
3341 ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
3342 ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
3343 ** a URI filename, its value overrides any behavior requested by setting
3344 ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
3345 **
3346 ** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
3347 ** [powersafe overwrite] property does or does not apply to the
3348 ** storage media on which the database file resides.
3349 **
3350 ** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
3351 ** which if set disables file locking in rollback journal modes. This
3352 ** is useful for accessing a database on a filesystem that does not
3353 ** support locking. Caution: Database corruption might result if two
3354 ** or more processes write to the same database and any one of those
3355 ** processes uses nolock=1.
3356 **
3357 ** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
3358 ** parameter that indicates that the database file is stored on
3359 ** read-only media. ^When immutable is set, SQLite assumes that the
3360 ** database file cannot be changed, even by a process with higher
3361 ** privilege, and so the database is opened read-only and all locking
3362 ** and change detection is disabled. Caution: Setting the immutable
3363 ** property on a database file that does in fact change can result
3364 ** in incorrect query results and/or [SQLITE_CORRUPT] errors.
3365 ** See also: [SQLITE_IOCAP_IMMUTABLE].
3366 **
3367 ** </ul>
3368 **
3369 ** ^Specifying an unknown parameter in the query component of a URI is not an
3370 ** error. Future versions of SQLite might understand additional query
3371 ** parameters. See "[query parameters with special meaning to SQLite]" for
3372 ** additional information.
3373 **
3374 ** [[URI filename examples]] <h3>URI filename examples</h3>
3375 **
3376 ** <table border="1" align=center cellpadding=5>
3377 ** <tr><th> URI filenames <th> Results
3378 ** <tr><td> file:data.db <td>
3379 ** Open the file "data.db" in the current directory.
3380 ** <tr><td> file:/home/fred/data.db<br>
3381 ** file:///home/fred/data.db <br>
3382 ** file://localhost/home/fred/data.db <br> <td>
3383 ** Open the database file "/home/fred/data.db".
3384 ** <tr><td> file://darkstar/home/fred/data.db <td>
3385 ** An error. "darkstar" is not a recognized authority.
3386 ** <tr><td style="white-space:nowrap">
3387 ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
3388 ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
3389 ** C:. Note that the %20 escaping in this example is not strictly
3390 ** necessary - space characters can be used literally
3391 ** in URI filenames.
3392 ** <tr><td> file:data.db?mode=ro&cache=private <td>
3393 ** Open file "data.db" in the current directory for read-only access.
3394 ** Regardless of whether or not shared-cache mode is enabled by
3395 ** default, use a private cache.
3396 ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
3397 ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
3398 ** that uses dot-files in place of posix advisory locking.
3399 ** <tr><td> file:data.db?mode=readonly <td>
3400 ** An error. "readonly" is not a valid option for the "mode" parameter.
3401 ** </table>
3402 **
3403 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
3404 ** query components of a URI. A hexadecimal escape sequence consists of a
3405 ** percent sign - "%" - followed by exactly two hexadecimal digits
3406 ** specifying an octet value. ^Before the path or query components of a
3407 ** URI filename are interpreted, they are encoded using UTF-8 and all
3408 ** hexadecimal escape sequences replaced by a single byte containing the
3409 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
3410 ** the results are undefined.
3411 **
3412 ** <b>Note to Windows users:</b> The encoding used for the filename argument
3413 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3414 ** codepage is currently defined. Filenames containing international
3415 ** characters must be converted to UTF-8 prior to passing them into
3416 ** sqlite3_open() or sqlite3_open_v2().
3417 **
3418 ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
3419 ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
3420 ** features that require the use of temporary files may fail.
3421 **
3422 ** See also: [sqlite3_temp_directory]
3423 */
3424 SQLITE_API int SQLITE_STDCALL sqlite3_open(
3425  const char *filename, /* Database filename (UTF-8) */
3426  sqlite3 **ppDb /* OUT: SQLite db handle */
3427 );
3428 SQLITE_API int SQLITE_STDCALL sqlite3_open16(
3429  const void *filename, /* Database filename (UTF-16) */
3430  sqlite3 **ppDb /* OUT: SQLite db handle */
3431 );
3432 SQLITE_API int SQLITE_STDCALL sqlite3_open_v2(
3433  const char *filename, /* Database filename (UTF-8) */
3434  sqlite3 **ppDb, /* OUT: SQLite db handle */
3435  int flags, /* Flags */
3436  const char *zVfs /* Name of VFS module to use */
3437 );
3438 
3439 /*
3440 ** CAPI3REF: Obtain Values For URI Parameters
3441 **
3442 ** These are utility routines, useful to VFS implementations, that check
3443 ** to see if a database file was a URI that contained a specific query
3444 ** parameter, and if so obtains the value of that query parameter.
3445 **
3446 ** If F is the database filename pointer passed into the xOpen() method of
3447 ** a VFS implementation when the flags parameter to xOpen() has one or
3448 ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
3449 ** P is the name of the query parameter, then
3450 ** sqlite3_uri_parameter(F,P) returns the value of the P
3451 ** parameter if it exists or a NULL pointer if P does not appear as a
3452 ** query parameter on F. If P is a query parameter of F
3453 ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
3454 ** a pointer to an empty string.
3455 **
3456 ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
3457 ** parameter and returns true (1) or false (0) according to the value
3458 ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
3459 ** value of query parameter P is one of "yes", "true", or "on" in any
3460 ** case or if the value begins with a non-zero number. The
3461 ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
3462 ** query parameter P is one of "no", "false", or "off" in any case or
3463 ** if the value begins with a numeric zero. If P is not a query
3464 ** parameter on F or if the value of P is does not match any of the
3465 ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
3466 **
3467 ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
3468 ** 64-bit signed integer and returns that integer, or D if P does not
3469 ** exist. If the value of P is something other than an integer, then
3470 ** zero is returned.
3471 **
3472 ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
3473 ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
3474 ** is not a database file pathname pointer that SQLite passed into the xOpen
3475 ** VFS method, then the behavior of this routine is undefined and probably
3476 ** undesirable.
3477 */
3478 SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilename, const char *zParam);
3479 SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
3480 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
3481 
3482 
3483 /*
3484 ** CAPI3REF: Error Codes And Messages
3485 ** METHOD: sqlite3
3486 **
3487 ** ^If the most recent sqlite3_* API call associated with
3488 ** [database connection] D failed, then the sqlite3_errcode(D) interface
3489 ** returns the numeric [result code] or [extended result code] for that
3490 ** API call.
3491 ** If the most recent API call was successful,
3492 ** then the return value from sqlite3_errcode() is undefined.
3493 ** ^The sqlite3_extended_errcode()
3494 ** interface is the same except that it always returns the
3495 ** [extended result code] even when extended result codes are
3496 ** disabled.
3497 **
3498 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3499 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
3500 ** ^(Memory to hold the error message string is managed internally.
3501 ** The application does not need to worry about freeing the result.
3502 ** However, the error string might be overwritten or deallocated by
3503 ** subsequent calls to other SQLite interface functions.)^
3504 **
3505 ** ^The sqlite3_errstr() interface returns the English-language text
3506 ** that describes the [result code], as UTF-8.
3507 ** ^(Memory to hold the error message string is managed internally
3508 ** and must not be freed by the application)^.
3509 **
3510 ** When the serialized [threading mode] is in use, it might be the
3511 ** case that a second error occurs on a separate thread in between
3512 ** the time of the first error and the call to these interfaces.
3513 ** When that happens, the second error will be reported since these
3514 ** interfaces always report the most recent result. To avoid
3515 ** this, each thread can obtain exclusive use of the [database connection] D
3516 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3517 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3518 ** all calls to the interfaces listed here are completed.
3519 **
3520 ** If an interface fails with SQLITE_MISUSE, that means the interface
3521 ** was invoked incorrectly by the application. In that case, the
3522 ** error code and message may or may not be set.
3523 */
3524 SQLITE_API int SQLITE_STDCALL sqlite3_errcode(sqlite3 *db);
3525 SQLITE_API int SQLITE_STDCALL sqlite3_extended_errcode(sqlite3 *db);
3526 SQLITE_API const char *SQLITE_STDCALL sqlite3_errmsg(sqlite3*);
3527 SQLITE_API const void *SQLITE_STDCALL sqlite3_errmsg16(sqlite3*);
3528 SQLITE_API const char *SQLITE_STDCALL sqlite3_errstr(int);
3529 
3530 /*
3531 ** CAPI3REF: Prepared Statement Object
3532 ** KEYWORDS: {prepared statement} {prepared statements}
3533 **
3534 ** An instance of this object represents a single SQL statement that
3535 ** has been compiled into binary form and is ready to be evaluated.
3536 **
3537 ** Think of each SQL statement as a separate computer program. The
3538 ** original SQL text is source code. A prepared statement object
3539 ** is the compiled object code. All SQL must be converted into a
3540 ** prepared statement before it can be run.
3541 **
3542 ** The life-cycle of a prepared statement object usually goes like this:
3543 **
3544 ** <ol>
3545 ** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
3546 ** <li> Bind values to [parameters] using the sqlite3_bind_*()
3547 ** interfaces.
3548 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3549 ** <li> Reset the prepared statement using [sqlite3_reset()] then go back
3550 ** to step 2. Do this zero or more times.
3551 ** <li> Destroy the object using [sqlite3_finalize()].
3552 ** </ol>
3553 */
3554 typedef struct sqlite3_stmt sqlite3_stmt;
3555 
3556 /*
3557 ** CAPI3REF: Run-time Limits
3558 ** METHOD: sqlite3
3559 **
3560 ** ^(This interface allows the size of various constructs to be limited
3561 ** on a connection by connection basis. The first parameter is the
3562 ** [database connection] whose limit is to be set or queried. The
3563 ** second parameter is one of the [limit categories] that define a
3564 ** class of constructs to be size limited. The third parameter is the
3565 ** new limit for that construct.)^
3566 **
3567 ** ^If the new limit is a negative number, the limit is unchanged.
3568 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
3569 ** [limits | hard upper bound]
3570 ** set at compile-time by a C preprocessor macro called
3571 ** [limits | SQLITE_MAX_<i>NAME</i>].
3572 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3573 ** ^Attempts to increase a limit above its hard upper bound are
3574 ** silently truncated to the hard upper bound.
3575 **
3576 ** ^Regardless of whether or not the limit was changed, the
3577 ** [sqlite3_limit()] interface returns the prior value of the limit.
3578 ** ^Hence, to find the current value of a limit without changing it,
3579 ** simply invoke this interface with the third parameter set to -1.
3580 **
3581 ** Run-time limits are intended for use in applications that manage
3582 ** both their own internal database and also databases that are controlled
3583 ** by untrusted external sources. An example application might be a
3584 ** web browser that has its own databases for storing history and
3585 ** separate databases controlled by JavaScript applications downloaded
3586 ** off the Internet. The internal databases can be given the
3587 ** large, default limits. Databases managed by external sources can
3588 ** be given much smaller limits designed to prevent a denial of service
3589 ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
3590 ** interface to further control untrusted SQL. The size of the database
3591 ** created by an untrusted script can be contained using the
3592 ** [max_page_count] [PRAGMA].
3593 **
3594 ** New run-time limit categories may be added in future releases.
3595 */
3596 SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3*, int id, int newVal);
3597 
3598 /*
3599 ** CAPI3REF: Run-Time Limit Categories
3600 ** KEYWORDS: {limit category} {*limit categories}
3601 **
3602 ** These constants define various performance limits
3603 ** that can be lowered at run-time using [sqlite3_limit()].
3604 ** The synopsis of the meanings of the various limits is shown below.
3605 ** Additional information is available at [limits | Limits in SQLite].
3606 **
3607 ** <dl>
3608 ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3609 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3610 **
3611 ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3612 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3613 **
3614 ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3615 ** <dd>The maximum number of columns in a table definition or in the
3616 ** result set of a [SELECT] or the maximum number of columns in an index
3617 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3618 **
3619 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3620 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3621 **
3622 ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3623 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3624 **
3625 ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3626 ** <dd>The maximum number of instructions in a virtual machine program
3627 ** used to implement an SQL statement. This limit is not currently
3628 ** enforced, though that might be added in some future release of
3629 ** SQLite.</dd>)^
3630 **
3631 ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3632 ** <dd>The maximum number of arguments on a function.</dd>)^
3633 **
3634 ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3635 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3636 **
3637 ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3638 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3639 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3640 ** [GLOB] operators.</dd>)^
3641 **
3642 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3643 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3644 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3645 **
3646 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3647 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3648 **
3649 ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
3650 ** <dd>The maximum number of auxiliary worker threads that a single
3651 ** [prepared statement] may start.</dd>)^
3652 ** </dl>
3653 */
3654 #define SQLITE_LIMIT_LENGTH 0
3655 #define SQLITE_LIMIT_SQL_LENGTH 1
3656 #define SQLITE_LIMIT_COLUMN 2
3657 #define SQLITE_LIMIT_EXPR_DEPTH 3
3658 #define SQLITE_LIMIT_COMPOUND_SELECT 4
3659 #define SQLITE_LIMIT_VDBE_OP 5
3660 #define SQLITE_LIMIT_FUNCTION_ARG 6
3661 #define SQLITE_LIMIT_ATTACHED 7
3662 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
3663 #define SQLITE_LIMIT_VARIABLE_NUMBER 9
3664 #define SQLITE_LIMIT_TRIGGER_DEPTH 10
3665 #define SQLITE_LIMIT_WORKER_THREADS 11
3666 
3667 /*
3668 ** CAPI3REF: Compiling An SQL Statement
3669 ** KEYWORDS: {SQL statement compiler}
3670 ** METHOD: sqlite3
3671 ** CONSTRUCTOR: sqlite3_stmt
3672 **
3673 ** To execute an SQL query, it must first be compiled into a byte-code
3674 ** program using one of these routines.
3675 **
3676 ** The first argument, "db", is a [database connection] obtained from a
3677 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3678 ** [sqlite3_open16()]. The database connection must not have been closed.
3679 **
3680 ** The second argument, "zSql", is the statement to be compiled, encoded
3681 ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
3682 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3683 ** use UTF-16.
3684 **
3685 ** ^If the nByte argument is negative, then zSql is read up to the
3686 ** first zero terminator. ^If nByte is positive, then it is the
3687 ** number of bytes read from zSql. ^If nByte is zero, then no prepared
3688 ** statement is generated.
3689 ** If the caller knows that the supplied string is nul-terminated, then
3690 ** there is a small performance advantage to passing an nByte parameter that
3691 ** is the number of bytes in the input string <i>including</i>
3692 ** the nul-terminator.
3693 **
3694 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3695 ** past the end of the first SQL statement in zSql. These routines only
3696 ** compile the first statement in zSql, so *pzTail is left pointing to
3697 ** what remains uncompiled.
3698 **
3699 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3700 ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
3701 ** to NULL. ^If the input text contains no SQL (if the input is an empty
3702 ** string or a comment) then *ppStmt is set to NULL.
3703 ** The calling procedure is responsible for deleting the compiled
3704 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3705 ** ppStmt may not be NULL.
3706 **
3707 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3708 ** otherwise an [error code] is returned.
3709 **
3710 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3711 ** recommended for all new programs. The two older interfaces are retained
3712 ** for backwards compatibility, but their use is discouraged.
3713 ** ^In the "v2" interfaces, the prepared statement
3714 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3715 ** original SQL text. This causes the [sqlite3_step()] interface to
3716 ** behave differently in three ways:
3717 **
3718 ** <ol>
3719 ** <li>
3720 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3721 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3722 ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
3723 ** retries will occur before sqlite3_step() gives up and returns an error.
3724 ** </li>
3725 **
3726 ** <li>
3727 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3728 ** [error codes] or [extended error codes]. ^The legacy behavior was that
3729 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3730 ** and the application would have to make a second call to [sqlite3_reset()]
3731 ** in order to find the underlying cause of the problem. With the "v2" prepare
3732 ** interfaces, the underlying reason for the error is returned immediately.
3733 ** </li>
3734 **
3735 ** <li>
3736 ** ^If the specific value bound to [parameter | host parameter] in the
3737 ** WHERE clause might influence the choice of query plan for a statement,
3738 ** then the statement will be automatically recompiled, as if there had been
3739 ** a schema change, on the first [sqlite3_step()] call following any change
3740 ** to the [sqlite3_bind_text | bindings] of that [parameter].
3741 ** ^The specific value of WHERE-clause [parameter] might influence the
3742 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3743 ** or [GLOB] operator or if the parameter is compared to an indexed column
3744 ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
3745 ** </li>
3746 ** </ol>
3747 */
3748 SQLITE_API int SQLITE_STDCALL sqlite3_prepare(
3749  sqlite3 *db, /* Database handle */
3750  const char *zSql, /* SQL statement, UTF-8 encoded */
3751  int nByte, /* Maximum length of zSql in bytes. */
3752  sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3753  const char **pzTail /* OUT: Pointer to unused portion of zSql */
3754 );
3755 SQLITE_API int SQLITE_STDCALL sqlite3_prepare_v2(
3756  sqlite3 *db, /* Database handle */
3757  const char *zSql, /* SQL statement, UTF-8 encoded */
3758  int nByte, /* Maximum length of zSql in bytes. */
3759  sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3760  const char **pzTail /* OUT: Pointer to unused portion of zSql */
3761 );
3762 SQLITE_API int SQLITE_STDCALL sqlite3_prepare16(
3763  sqlite3 *db, /* Database handle */
3764  const void *zSql, /* SQL statement, UTF-16 encoded */
3765  int nByte, /* Maximum length of zSql in bytes. */
3766  sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3767  const void **pzTail /* OUT: Pointer to unused portion of zSql */
3768 );
3769 SQLITE_API int SQLITE_STDCALL sqlite3_prepare16_v2(
3770  sqlite3 *db, /* Database handle */
3771  const void *zSql, /* SQL statement, UTF-16 encoded */
3772  int nByte, /* Maximum length of zSql in bytes. */
3773  sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3774  const void **pzTail /* OUT: Pointer to unused portion of zSql */
3775 );
3776 
3777 /*
3778 ** CAPI3REF: Retrieving Statement SQL
3779 ** METHOD: sqlite3_stmt
3780 **
3781 ** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
3782 ** SQL text used to create [prepared statement] P if P was
3783 ** created by either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3784 ** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
3785 ** string containing the SQL text of prepared statement P with
3786 ** [bound parameters] expanded.
3787 **
3788 ** ^(For example, if a prepared statement is created using the SQL
3789 ** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
3790 ** and parameter :xyz is unbound, then sqlite3_sql() will return
3791 ** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
3792 ** will return "SELECT 2345,NULL".)^
3793 **
3794 ** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory
3795 ** is available to hold the result, or if the result would exceed the
3796 ** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
3797 **
3798 ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
3799 ** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time
3800 ** option causes sqlite3_expanded_sql() to always return NULL.
3801 **
3802 ** ^The string returned by sqlite3_sql(P) is managed by SQLite and is
3803 ** automatically freed when the prepared statement is finalized.
3804 ** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
3805 ** is obtained from [sqlite3_malloc()] and must be free by the application
3806 ** by passing it to [sqlite3_free()].
3807 */
3808 SQLITE_API const char *SQLITE_STDCALL sqlite3_sql(sqlite3_stmt *pStmt);
3809 SQLITE_API char *SQLITE_STDCALL sqlite3_expanded_sql(sqlite3_stmt *pStmt);
3810 
3811 /*
3812 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3813 ** METHOD: sqlite3_stmt
3814 **
3815 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3816 ** and only if the [prepared statement] X makes no direct changes to
3817 ** the content of the database file.
3818 **
3819 ** Note that [application-defined SQL functions] or
3820 ** [virtual tables] might change the database indirectly as a side effect.
3821 ** ^(For example, if an application defines a function "eval()" that
3822 ** calls [sqlite3_exec()], then the following SQL statement would
3823 ** change the database file through side-effects:
3824 **
3825 ** <blockquote><pre>
3826 ** SELECT eval('DELETE FROM t1') FROM t2;
3827 ** </pre></blockquote>
3828 **
3829 ** But because the [SELECT] statement does not change the database file
3830 ** directly, sqlite3_stmt_readonly() would still return true.)^
3831 **
3832 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3833 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3834 ** since the statements themselves do not actually modify the database but
3835 ** rather they control the timing of when other statements modify the
3836 ** database. ^The [ATTACH] and [DETACH] statements also cause
3837 ** sqlite3_stmt_readonly() to return true since, while those statements
3838 ** change the configuration of a database connection, they do not make
3839 ** changes to the content of the database files on disk.
3840 */
3841 SQLITE_API int SQLITE_STDCALL sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3842 
3843 /*
3844 ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
3845 ** METHOD: sqlite3_stmt
3846 **
3847 ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
3848 ** [prepared statement] S has been stepped at least once using
3849 ** [sqlite3_step(S)] but has neither run to completion (returned
3850 ** [SQLITE_DONE] from [sqlite3_step(S)]) nor
3851 ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
3852 ** interface returns false if S is a NULL pointer. If S is not a
3853 ** NULL pointer and is not a pointer to a valid [prepared statement]
3854 ** object, then the behavior is undefined and probably undesirable.
3855 **
3856 ** This interface can be used in combination [sqlite3_next_stmt()]
3857 ** to locate all prepared statements associated with a database
3858 ** connection that are in need of being reset. This can be used,
3859 ** for example, in diagnostic routines to search for prepared
3860 ** statements that are holding a transaction open.
3861 */
3862 SQLITE_API int SQLITE_STDCALL sqlite3_stmt_busy(sqlite3_stmt*);
3863 
3864 /*
3865 ** CAPI3REF: Dynamically Typed Value Object
3866 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3867 **
3868 ** SQLite uses the sqlite3_value object to represent all values
3869 ** that can be stored in a database table. SQLite uses dynamic typing
3870 ** for the values it stores. ^Values stored in sqlite3_value objects
3871 ** can be integers, floating point values, strings, BLOBs, or NULL.
3872 **
3873 ** An sqlite3_value object may be either "protected" or "unprotected".
3874 ** Some interfaces require a protected sqlite3_value. Other interfaces
3875 ** will accept either a protected or an unprotected sqlite3_value.
3876 ** Every interface that accepts sqlite3_value arguments specifies
3877 ** whether or not it requires a protected sqlite3_value. The
3878 ** [sqlite3_value_dup()] interface can be used to construct a new
3879 ** protected sqlite3_value from an unprotected sqlite3_value.
3880 **
3881 ** The terms "protected" and "unprotected" refer to whether or not
3882 ** a mutex is held. An internal mutex is held for a protected
3883 ** sqlite3_value object but no mutex is held for an unprotected
3884 ** sqlite3_value object. If SQLite is compiled to be single-threaded
3885 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3886 ** or if SQLite is run in one of reduced mutex modes
3887 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3888 ** then there is no distinction between protected and unprotected
3889 ** sqlite3_value objects and they can be used interchangeably. However,
3890 ** for maximum code portability it is recommended that applications
3891 ** still make the distinction between protected and unprotected
3892 ** sqlite3_value objects even when not strictly required.
3893 **
3894 ** ^The sqlite3_value objects that are passed as parameters into the
3895 ** implementation of [application-defined SQL functions] are protected.
3896 ** ^The sqlite3_value object returned by
3897 ** [sqlite3_column_value()] is unprotected.
3898 ** Unprotected sqlite3_value objects may only be used with
3899 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3900 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3901 ** interfaces require protected sqlite3_value objects.
3902 */
3903 typedef struct Mem sqlite3_value;
3904 
3905 /*
3906 ** CAPI3REF: SQL Function Context Object
3907 **
3908 ** The context in which an SQL function executes is stored in an
3909 ** sqlite3_context object. ^A pointer to an sqlite3_context object
3910 ** is always first parameter to [application-defined SQL functions].
3911 ** The application-defined SQL function implementation will pass this
3912 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3913 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3914 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3915 ** and/or [sqlite3_set_auxdata()].
3916 */
3917 typedef struct sqlite3_context sqlite3_context;
3918 
3919 /*
3920 ** CAPI3REF: Binding Values To Prepared Statements
3921 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3922 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3923 ** METHOD: sqlite3_stmt
3924 **
3925 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3926 ** literals may be replaced by a [parameter] that matches one of following
3927 ** templates:
3928 **
3929 ** <ul>
3930 ** <li> ?
3931 ** <li> ?NNN
3932 ** <li> :VVV
3933 ** <li> @VVV
3934 ** <li> $VVV
3935 ** </ul>
3936 **
3937 ** In the templates above, NNN represents an integer literal,
3938 ** and VVV represents an alphanumeric identifier.)^ ^The values of these
3939 ** parameters (also called "host parameter names" or "SQL parameters")
3940 ** can be set using the sqlite3_bind_*() routines defined here.
3941 **
3942 ** ^The first argument to the sqlite3_bind_*() routines is always
3943 ** a pointer to the [sqlite3_stmt] object returned from
3944 ** [sqlite3_prepare_v2()] or its variants.
3945 **
3946 ** ^The second argument is the index of the SQL parameter to be set.
3947 ** ^The leftmost SQL parameter has an index of 1. ^When the same named
3948 ** SQL parameter is used more than once, second and subsequent
3949 ** occurrences have the same index as the first occurrence.
3950 ** ^The index for named parameters can be looked up using the
3951 ** [sqlite3_bind_parameter_index()] API if desired. ^The index
3952 ** for "?NNN" parameters is the value of NNN.
3953 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3954 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3955 **
3956 ** ^The third argument is the value to bind to the parameter.
3957 ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3958 ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
3959 ** is ignored and the end result is the same as sqlite3_bind_null().
3960 **
3961 ** ^(In those routines that have a fourth argument, its value is the
3962 ** number of bytes in the parameter. To be clear: the value is the
3963 ** number of <u>bytes</u> in the value, not the number of characters.)^
3964 ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3965 ** is negative, then the length of the string is
3966 ** the number of bytes up to the first zero terminator.
3967 ** If the fourth parameter to sqlite3_bind_blob() is negative, then
3968 ** the behavior is undefined.
3969 ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
3970 ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
3971 ** that parameter must be the byte offset
3972 ** where the NUL terminator would occur assuming the string were NUL
3973 ** terminated. If any NUL characters occur at byte offsets less than
3974 ** the value of the fourth parameter then the resulting string value will
3975 ** contain embedded NULs. The result of expressions involving strings
3976 ** with embedded NULs is undefined.
3977 **
3978 ** ^The fifth argument to the BLOB and string binding interfaces
3979 ** is a destructor used to dispose of the BLOB or
3980 ** string after SQLite has finished with it. ^The destructor is called
3981 ** to dispose of the BLOB or string even if the call to bind API fails.
3982 ** ^If the fifth argument is
3983 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3984 ** information is in static, unmanaged space and does not need to be freed.
3985 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3986 ** SQLite makes its own private copy of the data immediately, before
3987 ** the sqlite3_bind_*() routine returns.
3988 **
3989 ** ^The sixth argument to sqlite3_bind_text64() must be one of
3990 ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
3991 ** to specify the encoding of the text in the third parameter. If
3992 ** the sixth argument to sqlite3_bind_text64() is not one of the
3993 ** allowed values shown above, or if the text encoding is different
3994 ** from the encoding specified by the sixth parameter, then the behavior
3995 ** is undefined.
3996 **
3997 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3998 ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
3999 ** (just an integer to hold its size) while it is being processed.
4000 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
4001 ** content is later written using
4002 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
4003 ** ^A negative value for the zeroblob results in a zero-length BLOB.
4004 **
4005 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
4006 ** for the [prepared statement] or with a prepared statement for which
4007 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
4008 ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
4009 ** routine is passed a [prepared statement] that has been finalized, the
4010 ** result is undefined and probably harmful.
4011 **
4012 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
4013 ** ^Unbound parameters are interpreted as NULL.
4014 **
4015 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
4016 ** [error code] if anything goes wrong.
4017 ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
4018 ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
4019 ** [SQLITE_MAX_LENGTH].
4020 ** ^[SQLITE_RANGE] is returned if the parameter
4021 ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
4022 **
4023 ** See also: [sqlite3_bind_parameter_count()],
4024 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
4025 */
4026 SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
4027 SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
4028  void(*)(void*));
4029 SQLITE_API int SQLITE_STDCALL sqlite3_bind_double(sqlite3_stmt*, int, double);
4030 SQLITE_API int SQLITE_STDCALL sqlite3_bind_int(sqlite3_stmt*, int, int);
4031 SQLITE_API int SQLITE_STDCALL sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
4032 SQLITE_API int SQLITE_STDCALL sqlite3_bind_null(sqlite3_stmt*, int);
4033 SQLITE_API int SQLITE_STDCALL sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
4034 SQLITE_API int SQLITE_STDCALL sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
4035 SQLITE_API int SQLITE_STDCALL sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
4036  void(*)(void*), unsigned char encoding);
4037 SQLITE_API int SQLITE_STDCALL sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
4038 SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
4039 SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
4040 
4041 /*
4042 ** CAPI3REF: Number Of SQL Parameters
4043 ** METHOD: sqlite3_stmt
4044 **
4045 ** ^This routine can be used to find the number of [SQL parameters]
4046 ** in a [prepared statement]. SQL parameters are tokens of the
4047 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
4048 ** placeholders for values that are [sqlite3_bind_blob | bound]
4049 ** to the parameters at a later time.
4050 **
4051 ** ^(This routine actually returns the index of the largest (rightmost)
4052 ** parameter. For all forms except ?NNN, this will correspond to the
4053 ** number of unique parameters. If parameters of the ?NNN form are used,
4054 ** there may be gaps in the list.)^
4055 **
4056 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
4057 ** [sqlite3_bind_parameter_name()], and
4058 ** [sqlite3_bind_parameter_index()].
4059 */
4060 SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_count(sqlite3_stmt*);
4061 
4062 /*
4063 ** CAPI3REF: Name Of A Host Parameter
4064 ** METHOD: sqlite3_stmt
4065 **
4066 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
4067 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
4068 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
4069 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
4070 ** respectively.
4071 ** In other words, the initial ":" or "$" or "@" or "?"
4072 ** is included as part of the name.)^
4073 ** ^Parameters of the form "?" without a following integer have no name
4074 ** and are referred to as "nameless" or "anonymous parameters".
4075 **
4076 ** ^The first host parameter has an index of 1, not 0.
4077 **
4078 ** ^If the value N is out of range or if the N-th parameter is
4079 ** nameless, then NULL is returned. ^The returned string is
4080 ** always in UTF-8 encoding even if the named parameter was
4081 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
4082 ** [sqlite3_prepare16_v2()].
4083 **
4084 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
4085 ** [sqlite3_bind_parameter_count()], and
4086 ** [sqlite3_bind_parameter_index()].
4087 */
4088 SQLITE_API const char *SQLITE_STDCALL sqlite3_bind_parameter_name(sqlite3_stmt*, int);
4089 
4090 /*
4091 ** CAPI3REF: Index Of A Parameter With A Given Name
4092 ** METHOD: sqlite3_stmt
4093 **
4094 ** ^Return the index of an SQL parameter given its name. ^The
4095 ** index value returned is suitable for use as the second
4096 ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
4097 ** is returned if no matching parameter is found. ^The parameter
4098 ** name must be given in UTF-8 even if the original statement
4099 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
4100 **
4101 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
4102 ** [sqlite3_bind_parameter_count()], and
4103 ** [sqlite3_bind_parameter_name()].
4104 */
4105 SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
4106 
4107 /*
4108 ** CAPI3REF: Reset All Bindings On A Prepared Statement
4109 ** METHOD: sqlite3_stmt
4110 **
4111 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
4112 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
4113 ** ^Use this routine to reset all host parameters to NULL.
4114 */
4115 SQLITE_API int SQLITE_STDCALL sqlite3_clear_bindings(sqlite3_stmt*);
4116 
4117 /*
4118 ** CAPI3REF: Number Of Columns In A Result Set
4119 ** METHOD: sqlite3_stmt
4120 **
4121 ** ^Return the number of columns in the result set returned by the
4122 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
4123 ** statement that does not return data (for example an [UPDATE]).
4124 **
4125 ** See also: [sqlite3_data_count()]
4126 */
4127 SQLITE_API int SQLITE_STDCALL sqlite3_column_count(sqlite3_stmt *pStmt);
4128 
4129 /*
4130 ** CAPI3REF: Column Names In A Result Set
4131 ** METHOD: sqlite3_stmt
4132 **
4133 ** ^These routines return the name assigned to a particular column
4134 ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
4135 ** interface returns a pointer to a zero-terminated UTF-8 string
4136 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
4137 ** UTF-16 string. ^The first parameter is the [prepared statement]
4138 ** that implements the [SELECT] statement. ^The second parameter is the
4139 ** column number. ^The leftmost column is number 0.
4140 **
4141 ** ^The returned string pointer is valid until either the [prepared statement]
4142 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
4143 ** reprepared by the first call to [sqlite3_step()] for a particular run
4144 ** or until the next call to
4145 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
4146 **
4147 ** ^If sqlite3_malloc() fails during the processing of either routine
4148 ** (for example during a conversion from UTF-8 to UTF-16) then a
4149 ** NULL pointer is returned.
4150 **
4151 ** ^The name of a result column is the value of the "AS" clause for
4152 ** that column, if there is an AS clause. If there is no AS clause
4153 ** then the name of the column is unspecified and may change from
4154 ** one release of SQLite to the next.
4155 */
4156 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_name(sqlite3_stmt*, int N);
4157 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_name16(sqlite3_stmt*, int N);
4158 
4159 /*
4160 ** CAPI3REF: Source Of Data In A Query Result
4161 ** METHOD: sqlite3_stmt
4162 **
4163 ** ^These routines provide a means to determine the database, table, and
4164 ** table column that is the origin of a particular result column in
4165 ** [SELECT] statement.
4166 ** ^The name of the database or table or column can be returned as
4167 ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
4168 ** the database name, the _table_ routines return the table name, and
4169 ** the origin_ routines return the column name.
4170 ** ^The returned string is valid until the [prepared statement] is destroyed
4171 ** using [sqlite3_finalize()] or until the statement is automatically
4172 ** reprepared by the first call to [sqlite3_step()] for a particular run
4173 ** or until the same information is requested
4174 ** again in a different encoding.
4175 **
4176 ** ^The names returned are the original un-aliased names of the
4177 ** database, table, and column.
4178 **
4179 ** ^The first argument to these interfaces is a [prepared statement].
4180 ** ^These functions return information about the Nth result column returned by
4181 ** the statement, where N is the second function argument.
4182 ** ^The left-most column is column 0 for these routines.
4183 **
4184 ** ^If the Nth column returned by the statement is an expression or
4185 ** subquery and is not a column value, then all of these functions return
4186 ** NULL. ^These routine might also return NULL if a memory allocation error
4187 ** occurs. ^Otherwise, they return the name of the attached database, table,
4188 ** or column that query result column was extracted from.
4189 **
4190 ** ^As with all other SQLite APIs, those whose names end with "16" return
4191 ** UTF-16 encoded strings and the other functions return UTF-8.
4192 **
4193 ** ^These APIs are only available if the library was compiled with the
4194 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
4195 **
4196 ** If two or more threads call one or more of these routines against the same
4197 ** prepared statement and column at the same time then the results are
4198 ** undefined.
4199 **
4200 ** If two or more threads call one or more
4201 ** [sqlite3_column_database_name | column metadata interfaces]
4202 ** for the same [prepared statement] and result column
4203 ** at the same time then the results are undefined.
4204 */
4205 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_database_name(sqlite3_stmt*,int);
4206 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_database_name16(sqlite3_stmt*,int);
4207 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_table_name(sqlite3_stmt*,int);
4208 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_table_name16(sqlite3_stmt*,int);
4209 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_origin_name(sqlite3_stmt*,int);
4210 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_origin_name16(sqlite3_stmt*,int);
4211 
4212 /*
4213 ** CAPI3REF: Declared Datatype Of A Query Result
4214 ** METHOD: sqlite3_stmt
4215 **
4216 ** ^(The first parameter is a [prepared statement].
4217 ** If this statement is a [SELECT] statement and the Nth column of the
4218 ** returned result set of that [SELECT] is a table column (not an
4219 ** expression or subquery) then the declared type of the table
4220 ** column is returned.)^ ^If the Nth column of the result set is an
4221 ** expression or subquery, then a NULL pointer is returned.
4222 ** ^The returned string is always UTF-8 encoded.
4223 **
4224 ** ^(For example, given the database schema:
4225 **
4226 ** CREATE TABLE t1(c1 VARIANT);
4227 **
4228 ** and the following statement to be compiled:
4229 **
4230 ** SELECT c1 + 1, c1 FROM t1;
4231 **
4232 ** this routine would return the string "VARIANT" for the second result
4233 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
4234 **
4235 ** ^SQLite uses dynamic run-time typing. ^So just because a column
4236 ** is declared to contain a particular type does not mean that the
4237 ** data stored in that column is of the declared type. SQLite is
4238 ** strongly typed, but the typing is dynamic not static. ^Type
4239 ** is associated with individual values, not with the containers
4240 ** used to hold those values.
4241 */
4242 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_decltype(sqlite3_stmt*,int);
4243 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_decltype16(sqlite3_stmt*,int);
4244 
4245 /*
4246 ** CAPI3REF: Evaluate An SQL Statement
4247 ** METHOD: sqlite3_stmt
4248 **
4249 ** After a [prepared statement] has been prepared using either
4250 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
4251 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
4252 ** must be called one or more times to evaluate the statement.
4253 **
4254 ** The details of the behavior of the sqlite3_step() interface depend
4255 ** on whether the statement was prepared using the newer "v2" interface
4256 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
4257 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
4258 ** new "v2" interface is recommended for new applications but the legacy
4259 ** interface will continue to be supported.
4260 **
4261 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
4262 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
4263 ** ^With the "v2" interface, any of the other [result codes] or
4264 ** [extended result codes] might be returned as well.
4265 **
4266 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
4267 ** database locks it needs to do its job. ^If the statement is a [COMMIT]
4268 ** or occurs outside of an explicit transaction, then you can retry the
4269 ** statement. If the statement is not a [COMMIT] and occurs within an
4270 ** explicit transaction then you should rollback the transaction before
4271 ** continuing.
4272 **
4273 ** ^[SQLITE_DONE] means that the statement has finished executing
4274 ** successfully. sqlite3_step() should not be called again on this virtual
4275 ** machine without first calling [sqlite3_reset()] to reset the virtual
4276 ** machine back to its initial state.
4277 **
4278 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
4279 ** is returned each time a new row of data is ready for processing by the
4280 ** caller. The values may be accessed using the [column access functions].
4281 ** sqlite3_step() is called again to retrieve the next row of data.
4282 **
4283 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
4284 ** violation) has occurred. sqlite3_step() should not be called again on
4285 ** the VM. More information may be found by calling [sqlite3_errmsg()].
4286 ** ^With the legacy interface, a more specific error code (for example,
4287 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
4288 ** can be obtained by calling [sqlite3_reset()] on the
4289 ** [prepared statement]. ^In the "v2" interface,
4290 ** the more specific error code is returned directly by sqlite3_step().
4291 **
4292 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
4293 ** Perhaps it was called on a [prepared statement] that has
4294 ** already been [sqlite3_finalize | finalized] or on one that had
4295 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
4296 ** be the case that the same database connection is being used by two or
4297 ** more threads at the same moment in time.
4298 **
4299 ** For all versions of SQLite up to and including 3.6.23.1, a call to
4300 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
4301 ** other than [SQLITE_ROW] before any subsequent invocation of
4302 ** sqlite3_step(). Failure to reset the prepared statement using
4303 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
4304 ** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began
4305 ** calling [sqlite3_reset()] automatically in this circumstance rather
4306 ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
4307 ** break because any application that ever receives an SQLITE_MISUSE error
4308 ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
4309 ** can be used to restore the legacy behavior.
4310 **
4311 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
4312 ** API always returns a generic error code, [SQLITE_ERROR], following any
4313 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
4314 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
4315 ** specific [error codes] that better describes the error.
4316 ** We admit that this is a goofy design. The problem has been fixed
4317 ** with the "v2" interface. If you prepare all of your SQL statements
4318 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
4319 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
4320 ** then the more specific [error codes] are returned directly
4321 ** by sqlite3_step(). The use of the "v2" interface is recommended.
4322 */
4323 SQLITE_API int SQLITE_STDCALL sqlite3_step(sqlite3_stmt*);
4324 
4325 /*
4326 ** CAPI3REF: Number of columns in a result set
4327 ** METHOD: sqlite3_stmt
4328 **
4329 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
4330 ** current row of the result set of [prepared statement] P.
4331 ** ^If prepared statement P does not have results ready to return
4332 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
4333 ** interfaces) then sqlite3_data_count(P) returns 0.
4334 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
4335 ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
4336 ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
4337 ** will return non-zero if previous call to [sqlite3_step](P) returned
4338 ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
4339 ** where it always returns zero since each step of that multi-step
4340 ** pragma returns 0 columns of data.
4341 **
4342 ** See also: [sqlite3_column_count()]
4343 */
4344 SQLITE_API int SQLITE_STDCALL sqlite3_data_count(sqlite3_stmt *pStmt);
4345 
4346 /*
4347 ** CAPI3REF: Fundamental Datatypes
4348 ** KEYWORDS: SQLITE_TEXT
4349 **
4350 ** ^(Every value in SQLite has one of five fundamental datatypes:
4351 **
4352 ** <ul>
4353 ** <li> 64-bit signed integer
4354 ** <li> 64-bit IEEE floating point number
4355 ** <li> string
4356 ** <li> BLOB
4357 ** <li> NULL
4358 ** </ul>)^
4359 **
4360 ** These constants are codes for each of those types.
4361 **
4362 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
4363 ** for a completely different meaning. Software that links against both
4364 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
4365 ** SQLITE_TEXT.
4366 */
4367 #define SQLITE_INTEGER 1
4368 #define SQLITE_FLOAT 2
4369 #define SQLITE_BLOB 4
4370 #define SQLITE_NULL 5
4371 #ifdef SQLITE_TEXT
4372 # undef SQLITE_TEXT
4373 #else
4374 # define SQLITE_TEXT 3
4375 #endif
4376 #define SQLITE3_TEXT 3
4377 
4378 /*
4379 ** CAPI3REF: Result Values From A Query
4380 ** KEYWORDS: {column access functions}
4381 ** METHOD: sqlite3_stmt
4382 **
4383 ** ^These routines return information about a single column of the current
4384 ** result row of a query. ^In every case the first argument is a pointer
4385 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
4386 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
4387 ** and the second argument is the index of the column for which information
4388 ** should be returned. ^The leftmost column of the result set has the index 0.
4389 ** ^The number of columns in the result can be determined using
4390 ** [sqlite3_column_count()].
4391 **
4392 ** If the SQL statement does not currently point to a valid row, or if the
4393 ** column index is out of range, the result is undefined.
4394 ** These routines may only be called when the most recent call to
4395 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
4396 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
4397 ** If any of these routines are called after [sqlite3_reset()] or
4398 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
4399 ** something other than [SQLITE_ROW], the results are undefined.
4400 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
4401 ** are called from a different thread while any of these routines
4402 ** are pending, then the results are undefined.
4403 **
4404 ** ^The sqlite3_column_type() routine returns the
4405 ** [SQLITE_INTEGER | datatype code] for the initial data type
4406 ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
4407 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
4408 ** returned by sqlite3_column_type() is only meaningful if no type
4409 ** conversions have occurred as described below. After a type conversion,
4410 ** the value returned by sqlite3_column_type() is undefined. Future
4411 ** versions of SQLite may change the behavior of sqlite3_column_type()
4412 ** following a type conversion.
4413 **
4414 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
4415 ** routine returns the number of bytes in that BLOB or string.
4416 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
4417 ** the string to UTF-8 and then returns the number of bytes.
4418 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
4419 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
4420 ** the number of bytes in that string.
4421 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
4422 **
4423 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
4424 ** routine returns the number of bytes in that BLOB or string.
4425 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
4426 ** the string to UTF-16 and then returns the number of bytes.
4427 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
4428 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
4429 ** the number of bytes in that string.
4430 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
4431 **
4432 ** ^The values returned by [sqlite3_column_bytes()] and
4433 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
4434 ** of the string. ^For clarity: the values returned by
4435 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
4436 ** bytes in the string, not the number of characters.
4437 **
4438 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4439 ** even empty strings, are always zero-terminated. ^The return
4440 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
4441 **
4442 ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
4443 ** [unprotected sqlite3_value] object. In a multithreaded environment,
4444 ** an unprotected sqlite3_value object may only be used safely with
4445 ** [sqlite3_bind_value()] and [sqlite3_result_value()].
4446 ** If the [unprotected sqlite3_value] object returned by
4447 ** [sqlite3_column_value()] is used in any other way, including calls
4448 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4449 ** or [sqlite3_value_bytes()], the behavior is not threadsafe.
4450 **
4451 ** These routines attempt to convert the value where appropriate. ^For
4452 ** example, if the internal representation is FLOAT and a text result
4453 ** is requested, [sqlite3_snprintf()] is used internally to perform the
4454 ** conversion automatically. ^(The following table details the conversions
4455 ** that are applied:
4456 **
4457 ** <blockquote>
4458 ** <table border="1">
4459 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
4460 **
4461 ** <tr><td> NULL <td> INTEGER <td> Result is 0
4462 ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
4463 ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
4464 ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
4465 ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
4466 ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
4467 ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
4468 ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
4469 ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
4470 ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
4471 ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
4472 ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
4473 ** <tr><td> TEXT <td> BLOB <td> No change
4474 ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
4475 ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
4476 ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
4477 ** </table>
4478 ** </blockquote>)^
4479 **
4480 ** Note that when type conversions occur, pointers returned by prior
4481 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4482 ** sqlite3_column_text16() may be invalidated.
4483 ** Type conversions and pointer invalidations might occur
4484 ** in the following cases:
4485 **
4486 ** <ul>
4487 ** <li> The initial content is a BLOB and sqlite3_column_text() or
4488 ** sqlite3_column_text16() is called. A zero-terminator might
4489 ** need to be added to the string.</li>
4490 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4491 ** sqlite3_column_text16() is called. The content must be converted
4492 ** to UTF-16.</li>
4493 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4494 ** sqlite3_column_text() is called. The content must be converted
4495 ** to UTF-8.</li>
4496 ** </ul>
4497 **
4498 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4499 ** not invalidate a prior pointer, though of course the content of the buffer
4500 ** that the prior pointer references will have been modified. Other kinds
4501 ** of conversion are done in place when it is possible, but sometimes they
4502 ** are not possible and in those cases prior pointers are invalidated.
4503 **
4504 ** The safest policy is to invoke these routines
4505 ** in one of the following ways:
4506 **
4507 ** <ul>
4508 ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4509 ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4510 ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4511 ** </ul>
4512 **
4513 ** In other words, you should call sqlite3_column_text(),
4514 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4515 ** into the desired format, then invoke sqlite3_column_bytes() or
4516 ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
4517 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4518 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4519 ** with calls to sqlite3_column_bytes().
4520 **
4521 ** ^The pointers returned are valid until a type conversion occurs as
4522 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4523 ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
4524 ** and BLOBs is freed automatically. Do <em>not</em> pass the pointers returned
4525 ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4526 ** [sqlite3_free()].
4527 **
4528 ** ^(If a memory allocation error occurs during the evaluation of any
4529 ** of these routines, a default value is returned. The default value
4530 ** is either the integer 0, the floating point number 0.0, or a NULL
4531 ** pointer. Subsequent calls to [sqlite3_errcode()] will return
4532 ** [SQLITE_NOMEM].)^
4533 */
4534 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_blob(sqlite3_stmt*, int iCol);
4535 SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4536 SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4537 SQLITE_API double SQLITE_STDCALL sqlite3_column_double(sqlite3_stmt*, int iCol);
4538 SQLITE_API int SQLITE_STDCALL sqlite3_column_int(sqlite3_stmt*, int iCol);
4539 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_column_int64(sqlite3_stmt*, int iCol);
4540 SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_column_text(sqlite3_stmt*, int iCol);
4541 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_text16(sqlite3_stmt*, int iCol);
4542 SQLITE_API int SQLITE_STDCALL sqlite3_column_type(sqlite3_stmt*, int iCol);
4543 SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_column_value(sqlite3_stmt*, int iCol);
4544 
4545 /*
4546 ** CAPI3REF: Destroy A Prepared Statement Object
4547 ** DESTRUCTOR: sqlite3_stmt
4548 **
4549 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
4550 ** ^If the most recent evaluation of the statement encountered no errors
4551 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
4552 ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
4553 ** sqlite3_finalize(S) returns the appropriate [error code] or
4554 ** [extended error code].
4555 **
4556 ** ^The sqlite3_finalize(S) routine can be called at any point during
4557 ** the life cycle of [prepared statement] S:
4558 ** before statement S is ever evaluated, after
4559 ** one or more calls to [sqlite3_reset()], or after any call
4560 ** to [sqlite3_step()] regardless of whether or not the statement has
4561 ** completed execution.
4562 **
4563 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
4564 **
4565 ** The application must finalize every [prepared statement] in order to avoid
4566 ** resource leaks. It is a grievous error for the application to try to use
4567 ** a prepared statement after it has been finalized. Any use of a prepared
4568 ** statement after it has been finalized can result in undefined and
4569 ** undesirable behavior such as segfaults and heap corruption.
4570 */
4571 SQLITE_API int SQLITE_STDCALL sqlite3_finalize(sqlite3_stmt *pStmt);
4572 
4573 /*
4574 ** CAPI3REF: Reset A Prepared Statement Object
4575 ** METHOD: sqlite3_stmt
4576 **
4577 ** The sqlite3_reset() function is called to reset a [prepared statement]
4578 ** object back to its initial state, ready to be re-executed.
4579 ** ^Any SQL statement variables that had values bound to them using
4580 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4581 ** Use [sqlite3_clear_bindings()] to reset the bindings.
4582 **
4583 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
4584 ** back to the beginning of its program.
4585 **
4586 ** ^If the most recent call to [sqlite3_step(S)] for the
4587 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4588 ** or if [sqlite3_step(S)] has never before been called on S,
4589 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
4590 **
4591 ** ^If the most recent call to [sqlite3_step(S)] for the
4592 ** [prepared statement] S indicated an error, then
4593 ** [sqlite3_reset(S)] returns an appropriate [error code].
4594 **
4595 ** ^The [sqlite3_reset(S)] interface does not change the values
4596 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4597 */
4598 SQLITE_API int SQLITE_STDCALL sqlite3_reset(sqlite3_stmt *pStmt);
4599 
4600 /*
4601 ** CAPI3REF: Create Or Redefine SQL Functions
4602 ** KEYWORDS: {function creation routines}
4603 ** KEYWORDS: {application-defined SQL function}
4604 ** KEYWORDS: {application-defined SQL functions}
4605 ** METHOD: sqlite3
4606 **
4607 ** ^These functions (collectively known as "function creation routines")
4608 ** are used to add SQL functions or aggregates or to redefine the behavior
4609 ** of existing SQL functions or aggregates. The only differences between
4610 ** these routines are the text encoding expected for
4611 ** the second parameter (the name of the function being created)
4612 ** and the presence or absence of a destructor callback for
4613 ** the application data pointer.
4614 **
4615 ** ^The first parameter is the [database connection] to which the SQL
4616 ** function is to be added. ^If an application uses more than one database
4617 ** connection then application-defined SQL functions must be added
4618 ** to each database connection separately.
4619 **
4620 ** ^The second parameter is the name of the SQL function to be created or
4621 ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
4622 ** representation, exclusive of the zero-terminator. ^Note that the name
4623 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
4624 ** ^Any attempt to create a function with a longer name
4625 ** will result in [SQLITE_MISUSE] being returned.
4626 **
4627 ** ^The third parameter (nArg)
4628 ** is the number of arguments that the SQL function or
4629 ** aggregate takes. ^If this parameter is -1, then the SQL function or
4630 ** aggregate may take any number of arguments between 0 and the limit
4631 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
4632 ** parameter is less than -1 or greater than 127 then the behavior is
4633 ** undefined.
4634 **
4635 ** ^The fourth parameter, eTextRep, specifies what
4636 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4637 ** its parameters. The application should set this parameter to
4638 ** [SQLITE_UTF16LE] if the function implementation invokes
4639 ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
4640 ** implementation invokes [sqlite3_value_text16be()] on an input, or
4641 ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
4642 ** otherwise. ^The same SQL function may be registered multiple times using
4643 ** different preferred text encodings, with different implementations for
4644 ** each encoding.
4645 ** ^When multiple implementations of the same function are available, SQLite
4646 ** will pick the one that involves the least amount of data conversion.
4647 **
4648 ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
4649 ** to signal that the function will always return the same result given
4650 ** the same inputs within a single SQL statement. Most SQL functions are
4651 ** deterministic. The built-in [random()] SQL function is an example of a
4652 ** function that is not deterministic. The SQLite query planner is able to
4653 ** perform additional optimizations on deterministic functions, so use
4654 ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
4655 **
4656 ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
4657 ** function can gain access to this pointer using [sqlite3_user_data()].)^
4658 **
4659 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4660 ** pointers to C-language functions that implement the SQL function or
4661 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4662 ** callback only; NULL pointers must be passed as the xStep and xFinal
4663 ** parameters. ^An aggregate SQL function requires an implementation of xStep
4664 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4665 ** SQL function or aggregate, pass NULL pointers for all three function
4666 ** callbacks.
4667 **
4668 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4669 ** then it is destructor for the application data pointer.
4670 ** The destructor is invoked when the function is deleted, either by being
4671 ** overloaded or when the database connection closes.)^
4672 ** ^The destructor is also invoked if the call to
4673 ** sqlite3_create_function_v2() fails.
4674 ** ^When the destructor callback of the tenth parameter is invoked, it
4675 ** is passed a single argument which is a copy of the application data
4676 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
4677 **
4678 ** ^It is permitted to register multiple implementations of the same
4679 ** functions with the same name but with either differing numbers of
4680 ** arguments or differing preferred text encodings. ^SQLite will use
4681 ** the implementation that most closely matches the way in which the
4682 ** SQL function is used. ^A function implementation with a non-negative
4683 ** nArg parameter is a better match than a function implementation with
4684 ** a negative nArg. ^A function where the preferred text encoding
4685 ** matches the database encoding is a better
4686 ** match than a function where the encoding is different.
4687 ** ^A function where the encoding difference is between UTF16le and UTF16be
4688 ** is a closer match than a function where the encoding difference is
4689 ** between UTF8 and UTF16.
4690 **
4691 ** ^Built-in functions may be overloaded by new application-defined functions.
4692 **
4693 ** ^An application-defined function is permitted to call other
4694 ** SQLite interfaces. However, such calls must not
4695 ** close the database connection nor finalize or reset the prepared
4696 ** statement in which the function is running.
4697 */
4698 SQLITE_API int SQLITE_STDCALL sqlite3_create_function(
4699  sqlite3 *db,
4700  const char *zFunctionName,
4701  int nArg,
4702  int eTextRep,
4703  void *pApp,
4704  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4705  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4706  void (*xFinal)(sqlite3_context*)
4707 );
4708 SQLITE_API int SQLITE_STDCALL sqlite3_create_function16(
4709  sqlite3 *db,
4710  const void *zFunctionName,
4711  int nArg,
4712  int eTextRep,
4713  void *pApp,
4714  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4715  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4716  void (*xFinal)(sqlite3_context*)
4717 );
4718 SQLITE_API int SQLITE_STDCALL sqlite3_create_function_v2(
4719  sqlite3 *db,
4720  const char *zFunctionName,
4721  int nArg,
4722  int eTextRep,
4723  void *pApp,
4724  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4725  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4726  void (*xFinal)(sqlite3_context*),
4727  void(*xDestroy)(void*)
4728 );
4729 
4730 /*
4731 ** CAPI3REF: Text Encodings
4732 **
4733 ** These constant define integer codes that represent the various
4734 ** text encodings supported by SQLite.
4735 */
4736 #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
4737 #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
4738 #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
4739 #define SQLITE_UTF16 4 /* Use native byte order */
4740 #define SQLITE_ANY 5 /* Deprecated */
4741 #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
4742 
4743 /*
4744 ** CAPI3REF: Function Flags
4745 **
4746 ** These constants may be ORed together with the
4747 ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
4748 ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
4749 ** [sqlite3_create_function_v2()].
4750 */
4751 #define SQLITE_DETERMINISTIC 0x800
4752 
4753 /*
4754 ** CAPI3REF: Deprecated Functions
4755 ** DEPRECATED
4756 **
4757 ** These functions are [deprecated]. In order to maintain
4758 ** backwards compatibility with older code, these functions continue
4759 ** to be supported. However, new applications should avoid
4760 ** the use of these functions. To encourage programmers to avoid
4761 ** these functions, we will not explain what they do.
4762 */
4763 #ifndef SQLITE_OMIT_DEPRECATED
4764 SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_aggregate_count(sqlite3_context*);
4765 SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_expired(sqlite3_stmt*);
4766 SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4767 SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_global_recover(void);
4768 SQLITE_API SQLITE_DEPRECATED void SQLITE_STDCALL sqlite3_thread_cleanup(void);
4769 SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
4770  void*,sqlite3_int64);
4771 #endif
4772 
4773 /*
4774 ** CAPI3REF: Obtaining SQL Values
4775 ** METHOD: sqlite3_value
4776 **
4777 ** The C-language implementation of SQL functions and aggregates uses
4778 ** this set of interface routines to access the parameter values on
4779 ** the function or aggregate.
4780 **
4781 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4782 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4783 ** define callbacks that implement the SQL functions and aggregates.
4784 ** The 3rd parameter to these callbacks is an array of pointers to
4785 ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
4786 ** each parameter to the SQL function. These routines are used to
4787 ** extract values from the [sqlite3_value] objects.
4788 **
4789 ** These routines work only with [protected sqlite3_value] objects.
4790 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4791 ** object results in undefined behavior.
4792 **
4793 ** ^These routines work just like the corresponding [column access functions]
4794 ** except that these routines take a single [protected sqlite3_value] object
4795 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4796 **
4797 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4798 ** in the native byte-order of the host machine. ^The
4799 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4800 ** extract UTF-16 strings as big-endian and little-endian respectively.
4801 **
4802 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
4803 ** numeric affinity to the value. This means that an attempt is
4804 ** made to convert the value to an integer or floating point. If
4805 ** such a conversion is possible without loss of information (in other
4806 ** words, if the value is a string that looks like a number)
4807 ** then the conversion is performed. Otherwise no conversion occurs.
4808 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4809 **
4810 ** Please pay particular attention to the fact that the pointer returned
4811 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4812 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4813 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4814 ** or [sqlite3_value_text16()].
4815 **
4816 ** These routines must be called from the same thread as
4817 ** the SQL function that supplied the [sqlite3_value*] parameters.
4818 */
4819 SQLITE_API const void *SQLITE_STDCALL sqlite3_value_blob(sqlite3_value*);
4820 SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes(sqlite3_value*);
4821 SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes16(sqlite3_value*);
4822 SQLITE_API double SQLITE_STDCALL sqlite3_value_double(sqlite3_value*);
4823 SQLITE_API int SQLITE_STDCALL sqlite3_value_int(sqlite3_value*);
4824 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_value_int64(sqlite3_value*);
4825 SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_value_text(sqlite3_value*);
4826 SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16(sqlite3_value*);
4827 SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16le(sqlite3_value*);
4828 SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16be(sqlite3_value*);
4829 SQLITE_API int SQLITE_STDCALL sqlite3_value_type(sqlite3_value*);
4830 SQLITE_API int SQLITE_STDCALL sqlite3_value_numeric_type(sqlite3_value*);
4831 
4832 /*
4833 ** CAPI3REF: Finding The Subtype Of SQL Values
4834 ** METHOD: sqlite3_value
4835 **
4836 ** The sqlite3_value_subtype(V) function returns the subtype for
4837 ** an [application-defined SQL function] argument V. The subtype
4838 ** information can be used to pass a limited amount of context from
4839 ** one SQL function to another. Use the [sqlite3_result_subtype()]
4840 ** routine to set the subtype for the return value of an SQL function.
4841 **
4842 ** SQLite makes no use of subtype itself. It merely passes the subtype
4843 ** from the result of one [application-defined SQL function] into the
4844 ** input of another.
4845 */
4846 SQLITE_API unsigned int SQLITE_STDCALL sqlite3_value_subtype(sqlite3_value*);
4847 
4848 /*
4849 ** CAPI3REF: Copy And Free SQL Values
4850 ** METHOD: sqlite3_value
4851 **
4852 ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
4853 ** object D and returns a pointer to that copy. ^The [sqlite3_value] returned
4854 ** is a [protected sqlite3_value] object even if the input is not.
4855 ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
4856 ** memory allocation fails.
4857 **
4858 ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
4859 ** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer
4860 ** then sqlite3_value_free(V) is a harmless no-op.
4861 */
4862 SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_value_dup(const sqlite3_value*);
4863 SQLITE_API void SQLITE_STDCALL sqlite3_value_free(sqlite3_value*);
4864 
4865 /*
4866 ** CAPI3REF: Obtain Aggregate Function Context
4867 ** METHOD: sqlite3_context
4868 **
4869 ** Implementations of aggregate SQL functions use this
4870 ** routine to allocate memory for storing their state.
4871 **
4872 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
4873 ** for a particular aggregate function, SQLite
4874 ** allocates N of memory, zeroes out that memory, and returns a pointer
4875 ** to the new memory. ^On second and subsequent calls to
4876 ** sqlite3_aggregate_context() for the same aggregate function instance,
4877 ** the same buffer is returned. Sqlite3_aggregate_context() is normally
4878 ** called once for each invocation of the xStep callback and then one
4879 ** last time when the xFinal callback is invoked. ^(When no rows match
4880 ** an aggregate query, the xStep() callback of the aggregate function
4881 ** implementation is never called and xFinal() is called exactly once.
4882 ** In those cases, sqlite3_aggregate_context() might be called for the
4883 ** first time from within xFinal().)^
4884 **
4885 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
4886 ** when first called if N is less than or equal to zero or if a memory
4887 ** allocate error occurs.
4888 **
4889 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4890 ** determined by the N parameter on first successful call. Changing the
4891 ** value of N in subsequent call to sqlite3_aggregate_context() within
4892 ** the same aggregate function instance will not resize the memory
4893 ** allocation.)^ Within the xFinal callback, it is customary to set
4894 ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
4895 ** pointless memory allocations occur.
4896 **
4897 ** ^SQLite automatically frees the memory allocated by
4898 ** sqlite3_aggregate_context() when the aggregate query concludes.
4899 **
4900 ** The first parameter must be a copy of the
4901 ** [sqlite3_context | SQL function context] that is the first parameter
4902 ** to the xStep or xFinal callback routine that implements the aggregate
4903 ** function.
4904 **
4905 ** This routine must be called from the same thread in which
4906 ** the aggregate SQL function is running.
4907 */
4908 SQLITE_API void *SQLITE_STDCALL sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4909 
4910 /*
4911 ** CAPI3REF: User Data For Functions
4912 ** METHOD: sqlite3_context
4913 **
4914 ** ^The sqlite3_user_data() interface returns a copy of
4915 ** the pointer that was the pUserData parameter (the 5th parameter)
4916 ** of the [sqlite3_create_function()]
4917 ** and [sqlite3_create_function16()] routines that originally
4918 ** registered the application defined function.
4919 **
4920 ** This routine must be called from the same thread in which
4921 ** the application-defined function is running.
4922 */
4923 SQLITE_API void *SQLITE_STDCALL sqlite3_user_data(sqlite3_context*);
4924 
4925 /*
4926 ** CAPI3REF: Database Connection For Functions
4927 ** METHOD: sqlite3_context
4928 **
4929 ** ^The sqlite3_context_db_handle() interface returns a copy of
4930 ** the pointer to the [database connection] (the 1st parameter)
4931 ** of the [sqlite3_create_function()]
4932 ** and [sqlite3_create_function16()] routines that originally
4933 ** registered the application defined function.
4934 */
4935 SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_context_db_handle(sqlite3_context*);
4936 
4937 /*
4938 ** CAPI3REF: Function Auxiliary Data
4939 ** METHOD: sqlite3_context
4940 **
4941 ** These functions may be used by (non-aggregate) SQL functions to
4942 ** associate metadata with argument values. If the same value is passed to
4943 ** multiple invocations of the same SQL function during query execution, under
4944 ** some circumstances the associated metadata may be preserved. An example
4945 ** of where this might be useful is in a regular-expression matching
4946 ** function. The compiled version of the regular expression can be stored as
4947 ** metadata associated with the pattern string.
4948 ** Then as long as the pattern string remains the same,
4949 ** the compiled regular expression can be reused on multiple
4950 ** invocations of the same function.
4951 **
4952 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4953 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4954 ** value to the application-defined function. ^If there is no metadata
4955 ** associated with the function argument, this sqlite3_get_auxdata() interface
4956 ** returns a NULL pointer.
4957 **
4958 ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
4959 ** argument of the application-defined function. ^Subsequent
4960 ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
4961 ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
4962 ** NULL if the metadata has been discarded.
4963 ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
4964 ** SQLite will invoke the destructor function X with parameter P exactly
4965 ** once, when the metadata is discarded.
4966 ** SQLite is free to discard the metadata at any time, including: <ul>
4967 ** <li> ^(when the corresponding function parameter changes)^, or
4968 ** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
4969 ** SQL statement)^, or
4970 ** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
4971 ** parameter)^, or
4972 ** <li> ^(during the original sqlite3_set_auxdata() call when a memory
4973 ** allocation error occurs.)^ </ul>
4974 **
4975 ** Note the last bullet in particular. The destructor X in
4976 ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
4977 ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
4978 ** should be called near the end of the function implementation and the
4979 ** function implementation should not make any use of P after
4980 ** sqlite3_set_auxdata() has been called.
4981 **
4982 ** ^(In practice, metadata is preserved between function calls for
4983 ** function parameters that are compile-time constants, including literal
4984 ** values and [parameters] and expressions composed from the same.)^
4985 **
4986 ** These routines must be called from the same thread in which
4987 ** the SQL function is running.
4988 */
4989 SQLITE_API void *SQLITE_STDCALL sqlite3_get_auxdata(sqlite3_context*, int N);
4990 SQLITE_API void SQLITE_STDCALL sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4991 
4992 
4993 /*
4994 ** CAPI3REF: Constants Defining Special Destructor Behavior
4995 **
4996 ** These are special values for the destructor that is passed in as the
4997 ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
4998 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4999 ** and will never change. It does not need to be destroyed. ^The
5000 ** SQLITE_TRANSIENT value means that the content will likely change in
5001 ** the near future and that SQLite should make its own private copy of
5002 ** the content before returning.
5003 **
5004 ** The typedef is necessary to work around problems in certain
5005 ** C++ compilers.
5006 */
5007 typedef void (*sqlite3_destructor_type)(void*);
5008 #define SQLITE_STATIC ((sqlite3_destructor_type)0)
5009 #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
5010 
5011 /*
5012 ** CAPI3REF: Setting The Result Of An SQL Function
5013 ** METHOD: sqlite3_context
5014 **
5015 ** These routines are used by the xFunc or xFinal callbacks that
5016 ** implement SQL functions and aggregates. See
5017 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
5018 ** for additional information.
5019 **
5020 ** These functions work very much like the [parameter binding] family of
5021 ** functions used to bind values to host parameters in prepared statements.
5022 ** Refer to the [SQL parameter] documentation for additional information.
5023 **
5024 ** ^The sqlite3_result_blob() interface sets the result from
5025 ** an application-defined function to be the BLOB whose content is pointed
5026 ** to by the second parameter and which is N bytes long where N is the
5027 ** third parameter.
5028 **
5029 ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
5030 ** interfaces set the result of the application-defined function to be
5031 ** a BLOB containing all zero bytes and N bytes in size.
5032 **
5033 ** ^The sqlite3_result_double() interface sets the result from
5034 ** an application-defined function to be a floating point value specified
5035 ** by its 2nd argument.
5036 **
5037 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
5038 ** cause the implemented SQL function to throw an exception.
5039 ** ^SQLite uses the string pointed to by the
5040 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
5041 ** as the text of an error message. ^SQLite interprets the error
5042 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
5043 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
5044 ** byte order. ^If the third parameter to sqlite3_result_error()
5045 ** or sqlite3_result_error16() is negative then SQLite takes as the error
5046 ** message all text up through the first zero character.
5047 ** ^If the third parameter to sqlite3_result_error() or
5048 ** sqlite3_result_error16() is non-negative then SQLite takes that many
5049 ** bytes (not characters) from the 2nd parameter as the error message.
5050 ** ^The sqlite3_result_error() and sqlite3_result_error16()
5051 ** routines make a private copy of the error message text before
5052 ** they return. Hence, the calling function can deallocate or
5053 ** modify the text after they return without harm.
5054 ** ^The sqlite3_result_error_code() function changes the error code
5055 ** returned by SQLite as a result of an error in a function. ^By default,
5056 ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
5057 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
5058 **
5059 ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
5060 ** error indicating that a string or BLOB is too long to represent.
5061 **
5062 ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
5063 ** error indicating that a memory allocation failed.
5064 **
5065 ** ^The sqlite3_result_int() interface sets the return value
5066 ** of the application-defined function to be the 32-bit signed integer
5067 ** value given in the 2nd argument.
5068 ** ^The sqlite3_result_int64() interface sets the return value
5069 ** of the application-defined function to be the 64-bit signed integer
5070 ** value given in the 2nd argument.
5071 **
5072 ** ^The sqlite3_result_null() interface sets the return value
5073 ** of the application-defined function to be NULL.
5074 **
5075 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
5076 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
5077 ** set the return value of the application-defined function to be
5078 ** a text string which is represented as UTF-8, UTF-16 native byte order,
5079 ** UTF-16 little endian, or UTF-16 big endian, respectively.
5080 ** ^The sqlite3_result_text64() interface sets the return value of an
5081 ** application-defined function to be a text string in an encoding
5082 ** specified by the fifth (and last) parameter, which must be one
5083 ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
5084 ** ^SQLite takes the text result from the application from
5085 ** the 2nd parameter of the sqlite3_result_text* interfaces.
5086 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
5087 ** is negative, then SQLite takes result text from the 2nd parameter
5088 ** through the first zero character.
5089 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
5090 ** is non-negative, then as many bytes (not characters) of the text
5091 ** pointed to by the 2nd parameter are taken as the application-defined
5092 ** function result. If the 3rd parameter is non-negative, then it
5093 ** must be the byte offset into the string where the NUL terminator would
5094 ** appear if the string where NUL terminated. If any NUL characters occur
5095 ** in the string at a byte offset that is less than the value of the 3rd
5096 ** parameter, then the resulting string will contain embedded NULs and the
5097 ** result of expressions operating on strings with embedded NULs is undefined.
5098 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
5099 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
5100 ** function as the destructor on the text or BLOB result when it has
5101 ** finished using that result.
5102 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
5103 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
5104 ** assumes that the text or BLOB result is in constant space and does not
5105 ** copy the content of the parameter nor call a destructor on the content
5106 ** when it has finished using that result.
5107 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
5108 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
5109 ** then SQLite makes a copy of the result into space obtained from
5110 ** from [sqlite3_malloc()] before it returns.
5111 **
5112 ** ^The sqlite3_result_value() interface sets the result of
5113 ** the application-defined function to be a copy of the
5114 ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
5115 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
5116 ** so that the [sqlite3_value] specified in the parameter may change or
5117 ** be deallocated after sqlite3_result_value() returns without harm.
5118 ** ^A [protected sqlite3_value] object may always be used where an
5119 ** [unprotected sqlite3_value] object is required, so either
5120 ** kind of [sqlite3_value] object can be used with this interface.
5121 **
5122 ** If these routines are called from within the different thread
5123 ** than the one containing the application-defined function that received
5124 ** the [sqlite3_context] pointer, the results are undefined.
5125 */
5126 SQLITE_API void SQLITE_STDCALL sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
5127 SQLITE_API void SQLITE_STDCALL sqlite3_result_blob64(sqlite3_context*,const void*,
5128  sqlite3_uint64,void(*)(void*));
5129 SQLITE_API void SQLITE_STDCALL sqlite3_result_double(sqlite3_context*, double);
5130 SQLITE_API void SQLITE_STDCALL sqlite3_result_error(sqlite3_context*, const char*, int);
5131 SQLITE_API void SQLITE_STDCALL sqlite3_result_error16(sqlite3_context*, const void*, int);
5132 SQLITE_API void SQLITE_STDCALL sqlite3_result_error_toobig(sqlite3_context*);
5133 SQLITE_API void SQLITE_STDCALL sqlite3_result_error_nomem(sqlite3_context*);
5134 SQLITE_API void SQLITE_STDCALL sqlite3_result_error_code(sqlite3_context*, int);
5135 SQLITE_API void SQLITE_STDCALL sqlite3_result_int(sqlite3_context*, int);
5136 SQLITE_API void SQLITE_STDCALL sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
5137 SQLITE_API void SQLITE_STDCALL sqlite3_result_null(sqlite3_context*);
5138 SQLITE_API void SQLITE_STDCALL sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
5139 SQLITE_API void SQLITE_STDCALL sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
5140  void(*)(void*), unsigned char encoding);
5141 SQLITE_API void SQLITE_STDCALL sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
5142 SQLITE_API void SQLITE_STDCALL sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
5143 SQLITE_API void SQLITE_STDCALL sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
5144 SQLITE_API void SQLITE_STDCALL sqlite3_result_value(sqlite3_context*, sqlite3_value*);
5145 SQLITE_API void SQLITE_STDCALL sqlite3_result_zeroblob(sqlite3_context*, int n);
5146 SQLITE_API int SQLITE_STDCALL sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
5147 
5148 
5149 /*
5150 ** CAPI3REF: Setting The Subtype Of An SQL Function
5151 ** METHOD: sqlite3_context
5152 **
5153 ** The sqlite3_result_subtype(C,T) function causes the subtype of
5154 ** the result from the [application-defined SQL function] with
5155 ** [sqlite3_context] C to be the value T. Only the lower 8 bits
5156 ** of the subtype T are preserved in current versions of SQLite;
5157 ** higher order bits are discarded.
5158 ** The number of subtype bytes preserved by SQLite might increase
5159 ** in future releases of SQLite.
5160 */
5161 SQLITE_API void SQLITE_STDCALL sqlite3_result_subtype(sqlite3_context*,unsigned int);
5162 
5163 /*
5164 ** CAPI3REF: Define New Collating Sequences
5165 ** METHOD: sqlite3
5166 **
5167 ** ^These functions add, remove, or modify a [collation] associated
5168 ** with the [database connection] specified as the first argument.
5169 **
5170 ** ^The name of the collation is a UTF-8 string
5171 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
5172 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
5173 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
5174 ** considered to be the same name.
5175 **
5176 ** ^(The third argument (eTextRep) must be one of the constants:
5177 ** <ul>
5178 ** <li> [SQLITE_UTF8],
5179 ** <li> [SQLITE_UTF16LE],
5180 ** <li> [SQLITE_UTF16BE],
5181 ** <li> [SQLITE_UTF16], or
5182 ** <li> [SQLITE_UTF16_ALIGNED].
5183 ** </ul>)^
5184 ** ^The eTextRep argument determines the encoding of strings passed
5185 ** to the collating function callback, xCallback.
5186 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
5187 ** force strings to be UTF16 with native byte order.
5188 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
5189 ** on an even byte address.
5190 **
5191 ** ^The fourth argument, pArg, is an application data pointer that is passed
5192 ** through as the first argument to the collating function callback.
5193 **
5194 ** ^The fifth argument, xCallback, is a pointer to the collating function.
5195 ** ^Multiple collating functions can be registered using the same name but
5196 ** with different eTextRep parameters and SQLite will use whichever
5197 ** function requires the least amount of data transformation.
5198 ** ^If the xCallback argument is NULL then the collating function is
5199 ** deleted. ^When all collating functions having the same name are deleted,
5200 ** that collation is no longer usable.
5201 **
5202 ** ^The collating function callback is invoked with a copy of the pArg
5203 ** application data pointer and with two strings in the encoding specified
5204 ** by the eTextRep argument. The collating function must return an
5205 ** integer that is negative, zero, or positive
5206 ** if the first string is less than, equal to, or greater than the second,
5207 ** respectively. A collating function must always return the same answer
5208 ** given the same inputs. If two or more collating functions are registered
5209 ** to the same collation name (using different eTextRep values) then all
5210 ** must give an equivalent answer when invoked with equivalent strings.
5211 ** The collating function must obey the following properties for all
5212 ** strings A, B, and C:
5213 **
5214 ** <ol>
5215 ** <li> If A==B then B==A.
5216 ** <li> If A==B and B==C then A==C.
5217 ** <li> If A&lt;B THEN B&gt;A.
5218 ** <li> If A&lt;B and B&lt;C then A&lt;C.
5219 ** </ol>
5220 **
5221 ** If a collating function fails any of the above constraints and that
5222 ** collating function is registered and used, then the behavior of SQLite
5223 ** is undefined.
5224 **
5225 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
5226 ** with the addition that the xDestroy callback is invoked on pArg when
5227 ** the collating function is deleted.
5228 ** ^Collating functions are deleted when they are overridden by later
5229 ** calls to the collation creation functions or when the
5230 ** [database connection] is closed using [sqlite3_close()].
5231 **
5232 ** ^The xDestroy callback is <u>not</u> called if the
5233 ** sqlite3_create_collation_v2() function fails. Applications that invoke
5234 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
5235 ** check the return code and dispose of the application data pointer
5236 ** themselves rather than expecting SQLite to deal with it for them.
5237 ** This is different from every other SQLite interface. The inconsistency
5238 ** is unfortunate but cannot be changed without breaking backwards
5239 ** compatibility.
5240 **
5241 ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
5242 */
5243 SQLITE_API int SQLITE_STDCALL sqlite3_create_collation(
5244  sqlite3*,
5245  const char *zName,
5246  int eTextRep,
5247  void *pArg,
5248  int(*xCompare)(void*,int,const void*,int,const void*)
5249 );
5250 SQLITE_API int SQLITE_STDCALL sqlite3_create_collation_v2(
5251  sqlite3*,
5252  const char *zName,
5253  int eTextRep,
5254  void *pArg,
5255  int(*xCompare)(void*,int,const void*,int,const void*),
5256  void(*xDestroy)(void*)
5257 );
5258 SQLITE_API int SQLITE_STDCALL sqlite3_create_collation16(
5259  sqlite3*,
5260  const void *zName,
5261  int eTextRep,
5262  void *pArg,
5263  int(*xCompare)(void*,int,const void*,int,const void*)
5264 );
5265 
5266 /*
5267 ** CAPI3REF: Collation Needed Callbacks
5268 ** METHOD: sqlite3
5269 **
5270 ** ^To avoid having to register all collation sequences before a database
5271 ** can be used, a single callback function may be registered with the
5272 ** [database connection] to be invoked whenever an undefined collation
5273 ** sequence is required.
5274 **
5275 ** ^If the function is registered using the sqlite3_collation_needed() API,
5276 ** then it is passed the names of undefined collation sequences as strings
5277 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
5278 ** the names are passed as UTF-16 in machine native byte order.
5279 ** ^A call to either function replaces the existing collation-needed callback.
5280 **
5281 ** ^(When the callback is invoked, the first argument passed is a copy
5282 ** of the second argument to sqlite3_collation_needed() or
5283 ** sqlite3_collation_needed16(). The second argument is the database
5284 ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
5285 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
5286 ** sequence function required. The fourth parameter is the name of the
5287 ** required collation sequence.)^
5288 **
5289 ** The callback function should register the desired collation using
5290 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
5291 ** [sqlite3_create_collation_v2()].
5292 */
5293 SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed(
5294  sqlite3*,
5295  void*,
5296  void(*)(void*,sqlite3*,int eTextRep,const char*)
5297 );
5298 SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed16(
5299  sqlite3*,
5300  void*,
5301  void(*)(void*,sqlite3*,int eTextRep,const void*)
5302 );
5303 
5304 #ifdef SQLITE_HAS_CODEC
5305 /*
5306 ** Specify the key for an encrypted database. This routine should be
5307 ** called right after sqlite3_open().
5308 **
5309 ** The code to implement this API is not available in the public release
5310 ** of SQLite.
5311 */
5312 SQLITE_API int SQLITE_STDCALL sqlite3_key(
5313  sqlite3 *db, /* Database to be rekeyed */
5314  const void *pKey, int nKey /* The key */
5315 );
5316 SQLITE_API int SQLITE_STDCALL sqlite3_key_v2(
5317  sqlite3 *db, /* Database to be rekeyed */
5318  const char *zDbName, /* Name of the database */
5319  const void *pKey, int nKey /* The key */
5320 );
5321 
5322 /*
5323 ** Change the key on an open database. If the current database is not
5324 ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
5325 ** database is decrypted.
5326 **
5327 ** The code to implement this API is not available in the public release
5328 ** of SQLite.
5329 */
5330 SQLITE_API int SQLITE_STDCALL sqlite3_rekey(
5331  sqlite3 *db, /* Database to be rekeyed */
5332  const void *pKey, int nKey /* The new key */
5333 );
5334 SQLITE_API int SQLITE_STDCALL sqlite3_rekey_v2(
5335  sqlite3 *db, /* Database to be rekeyed */
5336  const char *zDbName, /* Name of the database */
5337  const void *pKey, int nKey /* The new key */
5338 );
5339 
5340 /*
5341 ** Specify the activation key for a SEE database. Unless
5342 ** activated, none of the SEE routines will work.
5343 */
5344 SQLITE_API void SQLITE_STDCALL sqlite3_activate_see(
5345  const char *zPassPhrase /* Activation phrase */
5346 );
5347 #endif
5348 
5349 #ifdef SQLITE_ENABLE_CEROD
5350 /*
5351 ** Specify the activation key for a CEROD database. Unless
5352 ** activated, none of the CEROD routines will work.
5353 */
5354 SQLITE_API void SQLITE_STDCALL sqlite3_activate_cerod(
5355  const char *zPassPhrase /* Activation phrase */
5356 );
5357 #endif
5358 
5359 /*
5360 ** CAPI3REF: Suspend Execution For A Short Time
5361 **
5362 ** The sqlite3_sleep() function causes the current thread to suspend execution
5363 ** for at least a number of milliseconds specified in its parameter.
5364 **
5365 ** If the operating system does not support sleep requests with
5366 ** millisecond time resolution, then the time will be rounded up to
5367 ** the nearest second. The number of milliseconds of sleep actually
5368 ** requested from the operating system is returned.
5369 **
5370 ** ^SQLite implements this interface by calling the xSleep()
5371 ** method of the default [sqlite3_vfs] object. If the xSleep() method
5372 ** of the default VFS is not implemented correctly, or not implemented at
5373 ** all, then the behavior of sqlite3_sleep() may deviate from the description
5374 ** in the previous paragraphs.
5375 */
5376 SQLITE_API int SQLITE_STDCALL sqlite3_sleep(int);
5377 
5378 /*
5379 ** CAPI3REF: Name Of The Folder Holding Temporary Files
5380 **
5381 ** ^(If this global variable is made to point to a string which is
5382 ** the name of a folder (a.k.a. directory), then all temporary files
5383 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
5384 ** will be placed in that directory.)^ ^If this variable
5385 ** is a NULL pointer, then SQLite performs a search for an appropriate
5386 ** temporary file directory.
5387 **
5388 ** Applications are strongly discouraged from using this global variable.
5389 ** It is required to set a temporary folder on Windows Runtime (WinRT).
5390 ** But for all other platforms, it is highly recommended that applications
5391 ** neither read nor write this variable. This global variable is a relic
5392 ** that exists for backwards compatibility of legacy applications and should
5393 ** be avoided in new projects.
5394 **
5395 ** It is not safe to read or modify this variable in more than one
5396 ** thread at a time. It is not safe to read or modify this variable
5397 ** if a [database connection] is being used at the same time in a separate
5398 ** thread.
5399 ** It is intended that this variable be set once
5400 ** as part of process initialization and before any SQLite interface
5401 ** routines have been called and that this variable remain unchanged
5402 ** thereafter.
5403 **
5404 ** ^The [temp_store_directory pragma] may modify this variable and cause
5405 ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
5406 ** the [temp_store_directory pragma] always assumes that any string
5407 ** that this variable points to is held in memory obtained from
5408 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5409 ** using [sqlite3_free].
5410 ** Hence, if this variable is modified directly, either it should be
5411 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5412 ** or else the use of the [temp_store_directory pragma] should be avoided.
5413 ** Except when requested by the [temp_store_directory pragma], SQLite
5414 ** does not free the memory that sqlite3_temp_directory points to. If
5415 ** the application wants that memory to be freed, it must do
5416 ** so itself, taking care to only do so after all [database connection]
5417 ** objects have been destroyed.
5418 **
5419 ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
5420 ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
5421 ** features that require the use of temporary files may fail. Here is an
5422 ** example of how to do this using C++ with the Windows Runtime:
5423 **
5424 ** <blockquote><pre>
5425 ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
5426 ** &nbsp; TemporaryFolder->Path->Data();
5427 ** char zPathBuf&#91;MAX_PATH + 1&#93;;
5428 ** memset(zPathBuf, 0, sizeof(zPathBuf));
5429 ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
5430 ** &nbsp; NULL, NULL);
5431 ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
5432 ** </pre></blockquote>
5433 */
5434 SQLITE_API char *sqlite3_temp_directory;
5435 
5436 /*
5437 ** CAPI3REF: Name Of The Folder Holding Database Files
5438 **
5439 ** ^(If this global variable is made to point to a string which is
5440 ** the name of a folder (a.k.a. directory), then all database files
5441 ** specified with a relative pathname and created or accessed by
5442 ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
5443 ** to be relative to that directory.)^ ^If this variable is a NULL
5444 ** pointer, then SQLite assumes that all database files specified
5445 ** with a relative pathname are relative to the current directory
5446 ** for the process. Only the windows VFS makes use of this global
5447 ** variable; it is ignored by the unix VFS.
5448 **
5449 ** Changing the value of this variable while a database connection is
5450 ** open can result in a corrupt database.
5451 **
5452 ** It is not safe to read or modify this variable in more than one
5453 ** thread at a time. It is not safe to read or modify this variable
5454 ** if a [database connection] is being used at the same time in a separate
5455 ** thread.
5456 ** It is intended that this variable be set once
5457 ** as part of process initialization and before any SQLite interface
5458 ** routines have been called and that this variable remain unchanged
5459 ** thereafter.
5460 **
5461 ** ^The [data_store_directory pragma] may modify this variable and cause
5462 ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
5463 ** the [data_store_directory pragma] always assumes that any string
5464 ** that this variable points to is held in memory obtained from
5465 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5466 ** using [sqlite3_free].
5467 ** Hence, if this variable is modified directly, either it should be
5468 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5469 ** or else the use of the [data_store_directory pragma] should be avoided.
5470 */
5471 SQLITE_API char *sqlite3_data_directory;
5472 
5473 /*
5474 ** CAPI3REF: Test For Auto-Commit Mode
5475 ** KEYWORDS: {autocommit mode}
5476 ** METHOD: sqlite3
5477 **
5478 ** ^The sqlite3_get_autocommit() interface returns non-zero or
5479 ** zero if the given database connection is or is not in autocommit mode,
5480 ** respectively. ^Autocommit mode is on by default.
5481 ** ^Autocommit mode is disabled by a [BEGIN] statement.
5482 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
5483 **
5484 ** If certain kinds of errors occur on a statement within a multi-statement
5485 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
5486 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
5487 ** transaction might be rolled back automatically. The only way to
5488 ** find out whether SQLite automatically rolled back the transaction after
5489 ** an error is to use this function.
5490 **
5491 ** If another thread changes the autocommit status of the database
5492 ** connection while this routine is running, then the return value
5493 ** is undefined.
5494 */
5495 SQLITE_API int SQLITE_STDCALL sqlite3_get_autocommit(sqlite3*);
5496 
5497 /*
5498 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
5499 ** METHOD: sqlite3_stmt
5500 **
5501 ** ^The sqlite3_db_handle interface returns the [database connection] handle
5502 ** to which a [prepared statement] belongs. ^The [database connection]
5503 ** returned by sqlite3_db_handle is the same [database connection]
5504 ** that was the first argument
5505 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
5506 ** create the statement in the first place.
5507 */
5508 SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_db_handle(sqlite3_stmt*);
5509 
5510 /*
5511 ** CAPI3REF: Return The Filename For A Database Connection
5512 ** METHOD: sqlite3
5513 **
5514 ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
5515 ** associated with database N of connection D. ^The main database file
5516 ** has the name "main". If there is no attached database N on the database
5517 ** connection D, or if database N is a temporary or in-memory database, then
5518 ** a NULL pointer is returned.
5519 **
5520 ** ^The filename returned by this function is the output of the
5521 ** xFullPathname method of the [VFS]. ^In other words, the filename
5522 ** will be an absolute pathname, even if the filename used
5523 ** to open the database originally was a URI or relative pathname.
5524 */
5525 SQLITE_API const char *SQLITE_STDCALL sqlite3_db_filename(sqlite3 *db, const char *zDbName);
5526 
5527 /*
5528 ** CAPI3REF: Determine if a database is read-only
5529 ** METHOD: sqlite3
5530 **
5531 ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
5532 ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
5533 ** the name of a database on connection D.
5534 */
5535 SQLITE_API int SQLITE_STDCALL sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
5536 
5537 /*
5538 ** CAPI3REF: Find the next prepared statement
5539 ** METHOD: sqlite3
5540 **
5541 ** ^This interface returns a pointer to the next [prepared statement] after
5542 ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
5543 ** then this interface returns a pointer to the first prepared statement
5544 ** associated with the database connection pDb. ^If no prepared statement
5545 ** satisfies the conditions of this routine, it returns NULL.
5546 **
5547 ** The [database connection] pointer D in a call to
5548 ** [sqlite3_next_stmt(D,S)] must refer to an open database
5549 ** connection and in particular must not be a NULL pointer.
5550 */
5551 SQLITE_API sqlite3_stmt *SQLITE_STDCALL sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
5552 
5553 /*
5554 ** CAPI3REF: Commit And Rollback Notification Callbacks
5555 ** METHOD: sqlite3
5556 **
5557 ** ^The sqlite3_commit_hook() interface registers a callback
5558 ** function to be invoked whenever a transaction is [COMMIT | committed].
5559 ** ^Any callback set by a previous call to sqlite3_commit_hook()
5560 ** for the same database connection is overridden.
5561 ** ^The sqlite3_rollback_hook() interface registers a callback
5562 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
5563 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
5564 ** for the same database connection is overridden.
5565 ** ^The pArg argument is passed through to the callback.
5566 ** ^If the callback on a commit hook function returns non-zero,
5567 ** then the commit is converted into a rollback.
5568 **
5569 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
5570 ** return the P argument from the previous call of the same function
5571 ** on the same [database connection] D, or NULL for
5572 ** the first call for each function on D.
5573 **
5574 ** The commit and rollback hook callbacks are not reentrant.
5575 ** The callback implementation must not do anything that will modify
5576 ** the database connection that invoked the callback. Any actions
5577 ** to modify the database connection must be deferred until after the
5578 ** completion of the [sqlite3_step()] call that triggered the commit
5579 ** or rollback hook in the first place.
5580 ** Note that running any other SQL statements, including SELECT statements,
5581 ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
5582 ** the database connections for the meaning of "modify" in this paragraph.
5583 **
5584 ** ^Registering a NULL function disables the callback.
5585 **
5586 ** ^When the commit hook callback routine returns zero, the [COMMIT]
5587 ** operation is allowed to continue normally. ^If the commit hook
5588 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
5589 ** ^The rollback hook is invoked on a rollback that results from a commit
5590 ** hook returning non-zero, just as it would be with any other rollback.
5591 **
5592 ** ^For the purposes of this API, a transaction is said to have been
5593 ** rolled back if an explicit "ROLLBACK" statement is executed, or
5594 ** an error or constraint causes an implicit rollback to occur.
5595 ** ^The rollback callback is not invoked if a transaction is
5596 ** automatically rolled back because the database connection is closed.
5597 **
5598 ** See also the [sqlite3_update_hook()] interface.
5599 */
5600 SQLITE_API void *SQLITE_STDCALL sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5601 SQLITE_API void *SQLITE_STDCALL sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5602 
5603 /*
5604 ** CAPI3REF: Data Change Notification Callbacks
5605 ** METHOD: sqlite3
5606 **
5607 ** ^The sqlite3_update_hook() interface registers a callback function
5608 ** with the [database connection] identified by the first argument
5609 ** to be invoked whenever a row is updated, inserted or deleted in
5610 ** a [rowid table].
5611 ** ^Any callback set by a previous call to this function
5612 ** for the same database connection is overridden.
5613 **
5614 ** ^The second argument is a pointer to the function to invoke when a
5615 ** row is updated, inserted or deleted in a rowid table.
5616 ** ^The first argument to the callback is a copy of the third argument
5617 ** to sqlite3_update_hook().
5618 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5619 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
5620 ** to be invoked.
5621 ** ^The third and fourth arguments to the callback contain pointers to the
5622 ** database and table name containing the affected row.
5623 ** ^The final callback parameter is the [rowid] of the row.
5624 ** ^In the case of an update, this is the [rowid] after the update takes place.
5625 **
5626 ** ^(The update hook is not invoked when internal system tables are
5627 ** modified (i.e. sqlite_master and sqlite_sequence).)^
5628 ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
5629 **
5630 ** ^In the current implementation, the update hook
5631 ** is not invoked when duplication rows are deleted because of an
5632 ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
5633 ** invoked when rows are deleted using the [truncate optimization].
5634 ** The exceptions defined in this paragraph might change in a future
5635 ** release of SQLite.
5636 **
5637 ** The update hook implementation must not do anything that will modify
5638 ** the database connection that invoked the update hook. Any actions
5639 ** to modify the database connection must be deferred until after the
5640 ** completion of the [sqlite3_step()] call that triggered the update hook.
5641 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5642 ** database connections for the meaning of "modify" in this paragraph.
5643 **
5644 ** ^The sqlite3_update_hook(D,C,P) function
5645 ** returns the P argument from the previous call
5646 ** on the same [database connection] D, or NULL for
5647 ** the first call on D.
5648 **
5649 ** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
5650 ** and [sqlite3_preupdate_hook()] interfaces.
5651 */
5652 SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
5653  sqlite3*,
5654  void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5655  void*
5656 );
5657 
5658 /*
5659 ** CAPI3REF: Enable Or Disable Shared Pager Cache
5660 **
5661 ** ^(This routine enables or disables the sharing of the database cache
5662 ** and schema data structures between [database connection | connections]
5663 ** to the same database. Sharing is enabled if the argument is true
5664 ** and disabled if the argument is false.)^
5665 **
5666 ** ^Cache sharing is enabled and disabled for an entire process.
5667 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5668 ** sharing was enabled or disabled for each thread separately.
5669 **
5670 ** ^(The cache sharing mode set by this interface effects all subsequent
5671 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5672 ** Existing database connections continue use the sharing mode
5673 ** that was in effect at the time they were opened.)^
5674 **
5675 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5676 ** successfully. An [error code] is returned otherwise.)^
5677 **
5678 ** ^Shared cache is disabled by default. But this might change in
5679 ** future releases of SQLite. Applications that care about shared
5680 ** cache setting should set it explicitly.
5681 **
5682 ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
5683 ** and will always return SQLITE_MISUSE. On those systems,
5684 ** shared cache mode should be enabled per-database connection via
5685 ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
5686 **
5687 ** This interface is threadsafe on processors where writing a
5688 ** 32-bit integer is atomic.
5689 **
5690 ** See Also: [SQLite Shared-Cache Mode]
5691 */
5692 SQLITE_API int SQLITE_STDCALL sqlite3_enable_shared_cache(int);
5693 
5694 /*
5695 ** CAPI3REF: Attempt To Free Heap Memory
5696 **
5697 ** ^The sqlite3_release_memory() interface attempts to free N bytes
5698 ** of heap memory by deallocating non-essential memory allocations
5699 ** held by the database library. Memory used to cache database
5700 ** pages to improve performance is an example of non-essential memory.
5701 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
5702 ** which might be more or less than the amount requested.
5703 ** ^The sqlite3_release_memory() routine is a no-op returning zero
5704 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5705 **
5706 ** See also: [sqlite3_db_release_memory()]
5707 */
5708 SQLITE_API int SQLITE_STDCALL sqlite3_release_memory(int);
5709 
5710 /*
5711 ** CAPI3REF: Free Memory Used By A Database Connection
5712 ** METHOD: sqlite3
5713 **
5714 ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
5715 ** memory as possible from database connection D. Unlike the
5716 ** [sqlite3_release_memory()] interface, this interface is in effect even
5717 ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
5718 ** omitted.
5719 **
5720 ** See also: [sqlite3_release_memory()]
5721 */
5722 SQLITE_API int SQLITE_STDCALL sqlite3_db_release_memory(sqlite3*);
5723 
5724 /*
5725 ** CAPI3REF: Impose A Limit On Heap Size
5726 **
5727 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5728 ** soft limit on the amount of heap memory that may be allocated by SQLite.
5729 ** ^SQLite strives to keep heap memory utilization below the soft heap
5730 ** limit by reducing the number of pages held in the page cache
5731 ** as heap memory usages approaches the limit.
5732 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
5733 ** below the limit, it will exceed the limit rather than generate
5734 ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
5735 ** is advisory only.
5736 **
5737 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
5738 ** the soft heap limit prior to the call, or negative in the case of an
5739 ** error. ^If the argument N is negative
5740 ** then no change is made to the soft heap limit. Hence, the current
5741 ** size of the soft heap limit can be determined by invoking
5742 ** sqlite3_soft_heap_limit64() with a negative argument.
5743 **
5744 ** ^If the argument N is zero then the soft heap limit is disabled.
5745 **
5746 ** ^(The soft heap limit is not enforced in the current implementation
5747 ** if one or more of following conditions are true:
5748 **
5749 ** <ul>
5750 ** <li> The soft heap limit is set to zero.
5751 ** <li> Memory accounting is disabled using a combination of the
5752 ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5753 ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5754 ** <li> An alternative page cache implementation is specified using
5755 ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
5756 ** <li> The page cache allocates from its own memory pool supplied
5757 ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5758 ** from the heap.
5759 ** </ul>)^
5760 **
5761 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
5762 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5763 ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5764 ** the soft heap limit is enforced on every memory allocation. Without
5765 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5766 ** when memory is allocated by the page cache. Testing suggests that because
5767 ** the page cache is the predominate memory user in SQLite, most
5768 ** applications will achieve adequate soft heap limit enforcement without
5769 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5770 **
5771 ** The circumstances under which SQLite will enforce the soft heap limit may
5772 ** changes in future releases of SQLite.
5773 */
5774 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_soft_heap_limit64(sqlite3_int64 N);
5775 
5776 /*
5777 ** CAPI3REF: Deprecated Soft Heap Limit Interface
5778 ** DEPRECATED
5779 **
5780 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5781 ** interface. This routine is provided for historical compatibility
5782 ** only. All new applications should use the
5783 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
5784 */
5785 SQLITE_API SQLITE_DEPRECATED void SQLITE_STDCALL sqlite3_soft_heap_limit(int N);
5786 
5787 
5788 /*
5789 ** CAPI3REF: Extract Metadata About A Column Of A Table
5790 ** METHOD: sqlite3
5791 **
5792 ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
5793 ** information about column C of table T in database D
5794 ** on [database connection] X.)^ ^The sqlite3_table_column_metadata()
5795 ** interface returns SQLITE_OK and fills in the non-NULL pointers in
5796 ** the final five arguments with appropriate values if the specified
5797 ** column exists. ^The sqlite3_table_column_metadata() interface returns
5798 ** SQLITE_ERROR and if the specified column does not exist.
5799 ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
5800 ** NULL pointer, then this routine simply checks for the existence of the
5801 ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
5802 ** does not.
5803 **
5804 ** ^The column is identified by the second, third and fourth parameters to
5805 ** this function. ^(The second parameter is either the name of the database
5806 ** (i.e. "main", "temp", or an attached database) containing the specified
5807 ** table or NULL.)^ ^If it is NULL, then all attached databases are searched
5808 ** for the table using the same algorithm used by the database engine to
5809 ** resolve unqualified table references.
5810 **
5811 ** ^The third and fourth parameters to this function are the table and column
5812 ** name of the desired column, respectively.
5813 **
5814 ** ^Metadata is returned by writing to the memory locations passed as the 5th
5815 ** and subsequent parameters to this function. ^Any of these arguments may be
5816 ** NULL, in which case the corresponding element of metadata is omitted.
5817 **
5818 ** ^(<blockquote>
5819 ** <table border="1">
5820 ** <tr><th> Parameter <th> Output<br>Type <th> Description
5821 **
5822 ** <tr><td> 5th <td> const char* <td> Data type
5823 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5824 ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
5825 ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
5826 ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
5827 ** </table>
5828 ** </blockquote>)^
5829 **
5830 ** ^The memory pointed to by the character pointers returned for the
5831 ** declaration type and collation sequence is valid until the next
5832 ** call to any SQLite API function.
5833 **
5834 ** ^If the specified table is actually a view, an [error code] is returned.
5835 **
5836 ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
5837 ** is not a [WITHOUT ROWID] table and an
5838 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5839 ** parameters are set for the explicitly declared column. ^(If there is no
5840 ** [INTEGER PRIMARY KEY] column, then the outputs
5841 ** for the [rowid] are set as follows:
5842 **
5843 ** <pre>
5844 ** data type: "INTEGER"
5845 ** collation sequence: "BINARY"
5846 ** not null: 0
5847 ** primary key: 1
5848 ** auto increment: 0
5849 ** </pre>)^
5850 **
5851 ** ^This function causes all database schemas to be read from disk and
5852 ** parsed, if that has not already been done, and returns an error if
5853 ** any errors are encountered while loading the schema.
5854 */
5855 SQLITE_API int SQLITE_STDCALL sqlite3_table_column_metadata(
5856  sqlite3 *db, /* Connection handle */
5857  const char *zDbName, /* Database name or NULL */
5858  const char *zTableName, /* Table name */
5859  const char *zColumnName, /* Column name */
5860  char const **pzDataType, /* OUTPUT: Declared data type */
5861  char const **pzCollSeq, /* OUTPUT: Collation sequence name */
5862  int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
5863  int *pPrimaryKey, /* OUTPUT: True if column part of PK */
5864  int *pAutoinc /* OUTPUT: True if column is auto-increment */
5865 );
5866 
5867 /*
5868 ** CAPI3REF: Load An Extension
5869 ** METHOD: sqlite3
5870 **
5871 ** ^This interface loads an SQLite extension library from the named file.
5872 **
5873 ** ^The sqlite3_load_extension() interface attempts to load an
5874 ** [SQLite extension] library contained in the file zFile. If
5875 ** the file cannot be loaded directly, attempts are made to load
5876 ** with various operating-system specific extensions added.
5877 ** So for example, if "samplelib" cannot be loaded, then names like
5878 ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
5879 ** be tried also.
5880 **
5881 ** ^The entry point is zProc.
5882 ** ^(zProc may be 0, in which case SQLite will try to come up with an
5883 ** entry point name on its own. It first tries "sqlite3_extension_init".
5884 ** If that does not work, it constructs a name "sqlite3_X_init" where the
5885 ** X is consists of the lower-case equivalent of all ASCII alphabetic
5886 ** characters in the filename from the last "/" to the first following
5887 ** "." and omitting any initial "lib".)^
5888 ** ^The sqlite3_load_extension() interface returns
5889 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5890 ** ^If an error occurs and pzErrMsg is not 0, then the
5891 ** [sqlite3_load_extension()] interface shall attempt to
5892 ** fill *pzErrMsg with error message text stored in memory
5893 ** obtained from [sqlite3_malloc()]. The calling function
5894 ** should free this memory by calling [sqlite3_free()].
5895 **
5896 ** ^Extension loading must be enabled using
5897 ** [sqlite3_enable_load_extension()] or
5898 ** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
5899 ** prior to calling this API,
5900 ** otherwise an error will be returned.
5901 **
5902 ** <b>Security warning:</b> It is recommended that the
5903 ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
5904 ** interface. The use of the [sqlite3_enable_load_extension()] interface
5905 ** should be avoided. This will keep the SQL function [load_extension()]
5906 ** disabled and prevent SQL injections from giving attackers
5907 ** access to extension loading capabilities.
5908 **
5909 ** See also the [load_extension() SQL function].
5910 */
5911 SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
5912  sqlite3 *db, /* Load the extension into this database connection */
5913  const char *zFile, /* Name of the shared library containing extension */
5914  const char *zProc, /* Entry point. Derived from zFile if 0 */
5915  char **pzErrMsg /* Put error message here if not 0 */
5916 );
5917 
5918 /*
5919 ** CAPI3REF: Enable Or Disable Extension Loading
5920 ** METHOD: sqlite3
5921 **
5922 ** ^So as not to open security holes in older applications that are
5923 ** unprepared to deal with [extension loading], and as a means of disabling
5924 ** [extension loading] while evaluating user-entered SQL, the following API
5925 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5926 **
5927 ** ^Extension loading is off by default.
5928 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5929 ** to turn extension loading on and call it with onoff==0 to turn
5930 ** it back off again.
5931 **
5932 ** ^This interface enables or disables both the C-API
5933 ** [sqlite3_load_extension()] and the SQL function [load_extension()].
5934 ** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
5935 ** to enable or disable only the C-API.)^
5936 **
5937 ** <b>Security warning:</b> It is recommended that extension loading
5938 ** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
5939 ** rather than this interface, so the [load_extension()] SQL function
5940 ** remains disabled. This will prevent SQL injections from giving attackers
5941 ** access to extension loading capabilities.
5942 */
5943 SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5944 
5945 /*
5946 ** CAPI3REF: Automatically Load Statically Linked Extensions
5947 **
5948 ** ^This interface causes the xEntryPoint() function to be invoked for
5949 ** each new [database connection] that is created. The idea here is that
5950 ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
5951 ** that is to be automatically loaded into all new database connections.
5952 **
5953 ** ^(Even though the function prototype shows that xEntryPoint() takes
5954 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
5955 ** arguments and expects an integer result as if the signature of the
5956 ** entry point where as follows:
5957 **
5958 ** <blockquote><pre>
5959 ** &nbsp; int xEntryPoint(
5960 ** &nbsp; sqlite3 *db,
5961 ** &nbsp; const char **pzErrMsg,
5962 ** &nbsp; const struct sqlite3_api_routines *pThunk
5963 ** &nbsp; );
5964 ** </pre></blockquote>)^
5965 **
5966 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5967 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5968 ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
5969 ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
5970 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
5971 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5972 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5973 **
5974 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5975 ** on the list of automatic extensions is a harmless no-op. ^No entry point
5976 ** will be called more than once for each database connection that is opened.
5977 **
5978 ** See also: [sqlite3_reset_auto_extension()]
5979 ** and [sqlite3_cancel_auto_extension()]
5980 */
5981 SQLITE_API int SQLITE_STDCALL sqlite3_auto_extension(void(*xEntryPoint)(void));
5982 
5983 /*
5984 ** CAPI3REF: Cancel Automatic Extension Loading
5985 **
5986 ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
5987 ** initialization routine X that was registered using a prior call to
5988 ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
5989 ** routine returns 1 if initialization routine X was successfully
5990 ** unregistered and it returns 0 if X was not on the list of initialization
5991 ** routines.
5992 */
5993 SQLITE_API int SQLITE_STDCALL sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));
5994 
5995 /*
5996 ** CAPI3REF: Reset Automatic Extension Loading
5997 **
5998 ** ^This interface disables all automatic extensions previously
5999 ** registered using [sqlite3_auto_extension()].
6000 */
6001 SQLITE_API void SQLITE_STDCALL sqlite3_reset_auto_extension(void);
6002 
6003 /*
6004 ** The interface to the virtual-table mechanism is currently considered
6005 ** to be experimental. The interface might change in incompatible ways.
6006 ** If this is a problem for you, do not use the interface at this time.
6007 **
6008 ** When the virtual-table mechanism stabilizes, we will declare the
6009 ** interface fixed, support it indefinitely, and remove this comment.
6010 */
6011 
6012 /*
6013 ** Structures used by the virtual table interface
6014 */
6015 typedef struct sqlite3_vtab sqlite3_vtab;
6016 typedef struct sqlite3_index_info sqlite3_index_info;
6017 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
6018 typedef struct sqlite3_module sqlite3_module;
6019 
6020 /*
6021 ** CAPI3REF: Virtual Table Object
6022 ** KEYWORDS: sqlite3_module {virtual table module}
6023 **
6024 ** This structure, sometimes called a "virtual table module",
6025 ** defines the implementation of a [virtual tables].
6026 ** This structure consists mostly of methods for the module.
6027 **
6028 ** ^A virtual table module is created by filling in a persistent
6029 ** instance of this structure and passing a pointer to that instance
6030 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
6031 ** ^The registration remains valid until it is replaced by a different
6032 ** module or until the [database connection] closes. The content
6033 ** of this structure must not change while it is registered with
6034 ** any database connection.
6035 */
6036 struct sqlite3_module {
6037  int iVersion;
6038  int (*xCreate)(sqlite3*, void *pAux,
6039  int argc, const char *const*argv,
6040  sqlite3_vtab **ppVTab, char**);
6041  int (*xConnect)(sqlite3*, void *pAux,
6042  int argc, const char *const*argv,
6043  sqlite3_vtab **ppVTab, char**);
6044  int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
6045  int (*xDisconnect)(sqlite3_vtab *pVTab);
6046  int (*xDestroy)(sqlite3_vtab *pVTab);
6047  int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
6048  int (*xClose)(sqlite3_vtab_cursor*);
6049  int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
6050  int argc, sqlite3_value **argv);
6051  int (*xNext)(sqlite3_vtab_cursor*);
6052  int (*xEof)(sqlite3_vtab_cursor*);
6053  int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
6054  int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
6055  int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
6056  int (*xBegin)(sqlite3_vtab *pVTab);
6057  int (*xSync)(sqlite3_vtab *pVTab);
6058  int (*xCommit)(sqlite3_vtab *pVTab);
6059  int (*xRollback)(sqlite3_vtab *pVTab);
6060  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
6061  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
6062  void **ppArg);
6063  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
6064  /* The methods above are in version 1 of the sqlite_module object. Those
6065  ** below are for version 2 and greater. */
6066  int (*xSavepoint)(sqlite3_vtab *pVTab, int);
6067  int (*xRelease)(sqlite3_vtab *pVTab, int);
6068  int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
6069 };
6070 
6071 /*
6072 ** CAPI3REF: Virtual Table Indexing Information
6073 ** KEYWORDS: sqlite3_index_info
6074 **
6075 ** The sqlite3_index_info structure and its substructures is used as part
6076 ** of the [virtual table] interface to
6077 ** pass information into and receive the reply from the [xBestIndex]
6078 ** method of a [virtual table module]. The fields under **Inputs** are the
6079 ** inputs to xBestIndex and are read-only. xBestIndex inserts its
6080 ** results into the **Outputs** fields.
6081 **
6082 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
6083 **
6084 ** <blockquote>column OP expr</blockquote>
6085 **
6086 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
6087 ** stored in aConstraint[].op using one of the
6088 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
6089 ** ^(The index of the column is stored in
6090 ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
6091 ** expr on the right-hand side can be evaluated (and thus the constraint
6092 ** is usable) and false if it cannot.)^
6093 **
6094 ** ^The optimizer automatically inverts terms of the form "expr OP column"
6095 ** and makes other simplifications to the WHERE clause in an attempt to
6096 ** get as many WHERE clause terms into the form shown above as possible.
6097 ** ^The aConstraint[] array only reports WHERE clause terms that are
6098 ** relevant to the particular virtual table being queried.
6099 **
6100 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
6101 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
6102 **
6103 ** The colUsed field indicates which columns of the virtual table may be
6104 ** required by the current scan. Virtual table columns are numbered from
6105 ** zero in the order in which they appear within the CREATE TABLE statement
6106 ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
6107 ** the corresponding bit is set within the colUsed mask if the column may be
6108 ** required by SQLite. If the table has at least 64 columns and any column
6109 ** to the right of the first 63 is required, then bit 63 of colUsed is also
6110 ** set. In other words, column iCol may be required if the expression
6111 ** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
6112 ** non-zero.
6113 **
6114 ** The [xBestIndex] method must fill aConstraintUsage[] with information
6115 ** about what parameters to pass to xFilter. ^If argvIndex>0 then
6116 ** the right-hand side of the corresponding aConstraint[] is evaluated
6117 ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
6118 ** is true, then the constraint is assumed to be fully handled by the
6119 ** virtual table and is not checked again by SQLite.)^
6120 **
6121 ** ^The idxNum and idxPtr values are recorded and passed into the
6122 ** [xFilter] method.
6123 ** ^[sqlite3_free()] is used to free idxPtr if and only if
6124 ** needToFreeIdxPtr is true.
6125 **
6126 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
6127 ** the correct order to satisfy the ORDER BY clause so that no separate
6128 ** sorting step is required.
6129 **
6130 ** ^The estimatedCost value is an estimate of the cost of a particular
6131 ** strategy. A cost of N indicates that the cost of the strategy is similar
6132 ** to a linear scan of an SQLite table with N rows. A cost of log(N)
6133 ** indicates that the expense of the operation is similar to that of a
6134 ** binary search on a unique indexed field of an SQLite table with N rows.
6135 **
6136 ** ^The estimatedRows value is an estimate of the number of rows that
6137 ** will be returned by the strategy.
6138 **
6139 ** The xBestIndex method may optionally populate the idxFlags field with a
6140 ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
6141 ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
6142 ** assumes that the strategy may visit at most one row.
6143 **
6144 ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
6145 ** SQLite also assumes that if a call to the xUpdate() method is made as
6146 ** part of the same statement to delete or update a virtual table row and the
6147 ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
6148 ** any database changes. In other words, if the xUpdate() returns
6149 ** SQLITE_CONSTRAINT, the database contents must be exactly as they were
6150 ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
6151 ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
6152 ** the xUpdate method are automatically rolled back by SQLite.
6153 **
6154 ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
6155 ** structure for SQLite version 3.8.2. If a virtual table extension is
6156 ** used with an SQLite version earlier than 3.8.2, the results of attempting
6157 ** to read or write the estimatedRows field are undefined (but are likely
6158 ** to included crashing the application). The estimatedRows field should
6159 ** therefore only be used if [sqlite3_libversion_number()] returns a
6160 ** value greater than or equal to 3008002. Similarly, the idxFlags field
6161 ** was added for version 3.9.0. It may therefore only be used if
6162 ** sqlite3_libversion_number() returns a value greater than or equal to
6163 ** 3009000.
6164 */
6165 struct sqlite3_index_info {
6166  /* Inputs */
6167  int nConstraint; /* Number of entries in aConstraint */
6169  int iColumn; /* Column constrained. -1 for ROWID */
6170  unsigned char op; /* Constraint operator */
6171  unsigned char usable; /* True if this constraint is usable */
6172  int iTermOffset; /* Used internally - xBestIndex should ignore */
6173  } *aConstraint; /* Table of WHERE clause constraints */
6174  int nOrderBy; /* Number of terms in the ORDER BY clause */
6176  int iColumn; /* Column number */
6177  unsigned char desc; /* True for DESC. False for ASC. */
6178  } *aOrderBy; /* The ORDER BY clause */
6179  /* Outputs */
6181  int argvIndex; /* if >0, constraint is part of argv to xFilter */
6182  unsigned char omit; /* Do not code a test for this constraint */
6183  } *aConstraintUsage;
6184  int idxNum; /* Number used to identify the index */
6185  char *idxStr; /* String, possibly obtained from sqlite3_malloc */
6186  int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
6187  int orderByConsumed; /* True if output is already ordered */
6188  double estimatedCost; /* Estimated cost of using this index */
6189  /* Fields below are only available in SQLite 3.8.2 and later */
6190  sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
6191  /* Fields below are only available in SQLite 3.9.0 and later */
6192  int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */
6193  /* Fields below are only available in SQLite 3.10.0 and later */
6194  sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */
6195 };
6196 
6197 /*
6198 ** CAPI3REF: Virtual Table Scan Flags
6199 */
6200 #define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */
6201 
6202 /*
6203 ** CAPI3REF: Virtual Table Constraint Operator Codes
6204 **
6205 ** These macros defined the allowed values for the
6206 ** [sqlite3_index_info].aConstraint[].op field. Each value represents
6207 ** an operator that is part of a constraint term in the wHERE clause of
6208 ** a query that uses a [virtual table].
6209 */
6210 #define SQLITE_INDEX_CONSTRAINT_EQ 2
6211 #define SQLITE_INDEX_CONSTRAINT_GT 4
6212 #define SQLITE_INDEX_CONSTRAINT_LE 8
6213 #define SQLITE_INDEX_CONSTRAINT_LT 16
6214 #define SQLITE_INDEX_CONSTRAINT_GE 32
6215 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
6216 #define SQLITE_INDEX_CONSTRAINT_LIKE 65
6217 #define SQLITE_INDEX_CONSTRAINT_GLOB 66
6218 #define SQLITE_INDEX_CONSTRAINT_REGEXP 67
6219 
6220 /*
6221 ** CAPI3REF: Register A Virtual Table Implementation
6222 ** METHOD: sqlite3
6223 **
6224 ** ^These routines are used to register a new [virtual table module] name.
6225 ** ^Module names must be registered before
6226 ** creating a new [virtual table] using the module and before using a
6227 ** preexisting [virtual table] for the module.
6228 **
6229 ** ^The module name is registered on the [database connection] specified
6230 ** by the first parameter. ^The name of the module is given by the
6231 ** second parameter. ^The third parameter is a pointer to
6232 ** the implementation of the [virtual table module]. ^The fourth
6233 ** parameter is an arbitrary client data pointer that is passed through
6234 ** into the [xCreate] and [xConnect] methods of the virtual table module
6235 ** when a new virtual table is be being created or reinitialized.
6236 **
6237 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
6238 ** is a pointer to a destructor for the pClientData. ^SQLite will
6239 ** invoke the destructor function (if it is not NULL) when SQLite
6240 ** no longer needs the pClientData pointer. ^The destructor will also
6241 ** be invoked if the call to sqlite3_create_module_v2() fails.
6242 ** ^The sqlite3_create_module()
6243 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
6244 ** destructor.
6245 */
6246 SQLITE_API int SQLITE_STDCALL sqlite3_create_module(
6247  sqlite3 *db, /* SQLite connection to register module with */
6248  const char *zName, /* Name of the module */
6249  const sqlite3_module *p, /* Methods for the module */
6250  void *pClientData /* Client data for xCreate/xConnect */
6251 );
6252 SQLITE_API int SQLITE_STDCALL sqlite3_create_module_v2(
6253  sqlite3 *db, /* SQLite connection to register module with */
6254  const char *zName, /* Name of the module */
6255  const sqlite3_module *p, /* Methods for the module */
6256  void *pClientData, /* Client data for xCreate/xConnect */
6257  void(*xDestroy)(void*) /* Module destructor function */
6258 );
6259 
6260 /*
6261 ** CAPI3REF: Virtual Table Instance Object
6262 ** KEYWORDS: sqlite3_vtab
6263 **
6264 ** Every [virtual table module] implementation uses a subclass
6265 ** of this object to describe a particular instance
6266 ** of the [virtual table]. Each subclass will
6267 ** be tailored to the specific needs of the module implementation.
6268 ** The purpose of this superclass is to define certain fields that are
6269 ** common to all module implementations.
6270 **
6271 ** ^Virtual tables methods can set an error message by assigning a
6272 ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
6273 ** take care that any prior string is freed by a call to [sqlite3_free()]
6274 ** prior to assigning a new string to zErrMsg. ^After the error message
6275 ** is delivered up to the client application, the string will be automatically
6276 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
6277 */
6278 struct sqlite3_vtab {
6279  const sqlite3_module *pModule; /* The module for this virtual table */
6280  int nRef; /* Number of open cursors */
6281  char *zErrMsg; /* Error message from sqlite3_mprintf() */
6282  /* Virtual table implementations will typically add additional fields */
6283 };
6284 
6285 /*
6286 ** CAPI3REF: Virtual Table Cursor Object
6287 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
6288 **
6289 ** Every [virtual table module] implementation uses a subclass of the
6290 ** following structure to describe cursors that point into the
6291 ** [virtual table] and are used
6292 ** to loop through the virtual table. Cursors are created using the
6293 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
6294 ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
6295 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
6296 ** of the module. Each module implementation will define
6297 ** the content of a cursor structure to suit its own needs.
6298 **
6299 ** This superclass exists in order to define fields of the cursor that
6300 ** are common to all implementations.
6301 */
6302 struct sqlite3_vtab_cursor {
6303  sqlite3_vtab *pVtab; /* Virtual table of this cursor */
6304  /* Virtual table implementations will typically add additional fields */
6305 };
6306 
6307 /*
6308 ** CAPI3REF: Declare The Schema Of A Virtual Table
6309 **
6310 ** ^The [xCreate] and [xConnect] methods of a
6311 ** [virtual table module] call this interface
6312 ** to declare the format (the names and datatypes of the columns) of
6313 ** the virtual tables they implement.
6314 */
6315 SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3*, const char *zSQL);
6316 
6317 /*
6318 ** CAPI3REF: Overload A Function For A Virtual Table
6319 ** METHOD: sqlite3
6320 **
6321 ** ^(Virtual tables can provide alternative implementations of functions
6322 ** using the [xFindFunction] method of the [virtual table module].
6323 ** But global versions of those functions
6324 ** must exist in order to be overloaded.)^
6325 **
6326 ** ^(This API makes sure a global version of a function with a particular
6327 ** name and number of parameters exists. If no such function exists
6328 ** before this API is called, a new function is created.)^ ^The implementation
6329 ** of the new function always causes an exception to be thrown. So
6330 ** the new function is not good for anything by itself. Its only
6331 ** purpose is to be a placeholder function that can be overloaded
6332 ** by a [virtual table].
6333 */
6334 SQLITE_API int SQLITE_STDCALL sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
6335 
6336 /*
6337 ** The interface to the virtual-table mechanism defined above (back up
6338 ** to a comment remarkably similar to this one) is currently considered
6339 ** to be experimental. The interface might change in incompatible ways.
6340 ** If this is a problem for you, do not use the interface at this time.
6341 **
6342 ** When the virtual-table mechanism stabilizes, we will declare the
6343 ** interface fixed, support it indefinitely, and remove this comment.
6344 */
6345 
6346 /*
6347 ** CAPI3REF: A Handle To An Open BLOB
6348 ** KEYWORDS: {BLOB handle} {BLOB handles}
6349 **
6350 ** An instance of this object represents an open BLOB on which
6351 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
6352 ** ^Objects of this type are created by [sqlite3_blob_open()]
6353 ** and destroyed by [sqlite3_blob_close()].
6354 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
6355 ** can be used to read or write small subsections of the BLOB.
6356 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
6357 */
6358 typedef struct sqlite3_blob sqlite3_blob;
6359 
6360 /*
6361 ** CAPI3REF: Open A BLOB For Incremental I/O
6362 ** METHOD: sqlite3
6363 ** CONSTRUCTOR: sqlite3_blob
6364 **
6365 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
6366 ** in row iRow, column zColumn, table zTable in database zDb;
6367 ** in other words, the same BLOB that would be selected by:
6368 **
6369 ** <pre>
6370 ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
6371 ** </pre>)^
6372 **
6373 ** ^(Parameter zDb is not the filename that contains the database, but
6374 ** rather the symbolic name of the database. For attached databases, this is
6375 ** the name that appears after the AS keyword in the [ATTACH] statement.
6376 ** For the main database file, the database name is "main". For TEMP
6377 ** tables, the database name is "temp".)^
6378 **
6379 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
6380 ** and write access. ^If the flags parameter is zero, the BLOB is opened for
6381 ** read-only access.
6382 **
6383 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
6384 ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
6385 ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
6386 ** the API is not misused, it is always safe to call [sqlite3_blob_close()]
6387 ** on *ppBlob after this function it returns.
6388 **
6389 ** This function fails with SQLITE_ERROR if any of the following are true:
6390 ** <ul>
6391 ** <li> ^(Database zDb does not exist)^,
6392 ** <li> ^(Table zTable does not exist within database zDb)^,
6393 ** <li> ^(Table zTable is a WITHOUT ROWID table)^,
6394 ** <li> ^(Column zColumn does not exist)^,
6395 ** <li> ^(Row iRow is not present in the table)^,
6396 ** <li> ^(The specified column of row iRow contains a value that is not
6397 ** a TEXT or BLOB value)^,
6398 ** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
6399 ** constraint and the blob is being opened for read/write access)^,
6400 ** <li> ^([foreign key constraints | Foreign key constraints] are enabled,
6401 ** column zColumn is part of a [child key] definition and the blob is
6402 ** being opened for read/write access)^.
6403 ** </ul>
6404 **
6405 ** ^Unless it returns SQLITE_MISUSE, this function sets the
6406 ** [database connection] error code and message accessible via
6407 ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
6408 **
6409 **
6410 ** ^(If the row that a BLOB handle points to is modified by an
6411 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
6412 ** then the BLOB handle is marked as "expired".
6413 ** This is true if any column of the row is changed, even a column
6414 ** other than the one the BLOB handle is open on.)^
6415 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
6416 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
6417 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
6418 ** rolled back by the expiration of the BLOB. Such changes will eventually
6419 ** commit if the transaction continues to completion.)^
6420 **
6421 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
6422 ** the opened blob. ^The size of a blob may not be changed by this
6423 ** interface. Use the [UPDATE] SQL command to change the size of a
6424 ** blob.
6425 **
6426 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
6427 ** and the built-in [zeroblob] SQL function may be used to create a
6428 ** zero-filled blob to read or write using the incremental-blob interface.
6429 **
6430 ** To avoid a resource leak, every open [BLOB handle] should eventually
6431 ** be released by a call to [sqlite3_blob_close()].
6432 */
6433 SQLITE_API int SQLITE_STDCALL sqlite3_blob_open(
6434  sqlite3*,
6435  const char *zDb,
6436  const char *zTable,
6437  const char *zColumn,
6438  sqlite3_int64 iRow,
6439  int flags,
6440  sqlite3_blob **ppBlob
6441 );
6442 
6443 /*
6444 ** CAPI3REF: Move a BLOB Handle to a New Row
6445 ** METHOD: sqlite3_blob
6446 **
6447 ** ^This function is used to move an existing blob handle so that it points
6448 ** to a different row of the same database table. ^The new row is identified
6449 ** by the rowid value passed as the second argument. Only the row can be
6450 ** changed. ^The database, table and column on which the blob handle is open
6451 ** remain the same. Moving an existing blob handle to a new row can be
6452 ** faster than closing the existing handle and opening a new one.
6453 **
6454 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
6455 ** it must exist and there must be either a blob or text value stored in
6456 ** the nominated column.)^ ^If the new row is not present in the table, or if
6457 ** it does not contain a blob or text value, or if another error occurs, an
6458 ** SQLite error code is returned and the blob handle is considered aborted.
6459 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
6460 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
6461 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
6462 ** always returns zero.
6463 **
6464 ** ^This function sets the database handle error code and message.
6465 */
6466 SQLITE_API int SQLITE_STDCALL sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
6467 
6468 /*
6469 ** CAPI3REF: Close A BLOB Handle
6470 ** DESTRUCTOR: sqlite3_blob
6471 **
6472 ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
6473 ** unconditionally. Even if this routine returns an error code, the
6474 ** handle is still closed.)^
6475 **
6476 ** ^If the blob handle being closed was opened for read-write access, and if
6477 ** the database is in auto-commit mode and there are no other open read-write
6478 ** blob handles or active write statements, the current transaction is
6479 ** committed. ^If an error occurs while committing the transaction, an error
6480 ** code is returned and the transaction rolled back.
6481 **
6482 ** Calling this function with an argument that is not a NULL pointer or an
6483 ** open blob handle results in undefined behaviour. ^Calling this routine
6484 ** with a null pointer (such as would be returned by a failed call to
6485 ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
6486 ** is passed a valid open blob handle, the values returned by the
6487 ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
6488 */
6489 SQLITE_API int SQLITE_STDCALL sqlite3_blob_close(sqlite3_blob *);
6490 
6491 /*
6492 ** CAPI3REF: Return The Size Of An Open BLOB
6493 ** METHOD: sqlite3_blob
6494 **
6495 ** ^Returns the size in bytes of the BLOB accessible via the
6496 ** successfully opened [BLOB handle] in its only argument. ^The
6497 ** incremental blob I/O routines can only read or overwriting existing
6498 ** blob content; they cannot change the size of a blob.
6499 **
6500 ** This routine only works on a [BLOB handle] which has been created
6501 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6502 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
6503 ** to this routine results in undefined and probably undesirable behavior.
6504 */
6505 SQLITE_API int SQLITE_STDCALL sqlite3_blob_bytes(sqlite3_blob *);
6506 
6507 /*
6508 ** CAPI3REF: Read Data From A BLOB Incrementally
6509 ** METHOD: sqlite3_blob
6510 **
6511 ** ^(This function is used to read data from an open [BLOB handle] into a
6512 ** caller-supplied buffer. N bytes of data are copied into buffer Z
6513 ** from the open BLOB, starting at offset iOffset.)^
6514 **
6515 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
6516 ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
6517 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
6518 ** ^The size of the blob (and hence the maximum value of N+iOffset)
6519 ** can be determined using the [sqlite3_blob_bytes()] interface.
6520 **
6521 ** ^An attempt to read from an expired [BLOB handle] fails with an
6522 ** error code of [SQLITE_ABORT].
6523 **
6524 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
6525 ** Otherwise, an [error code] or an [extended error code] is returned.)^
6526 **
6527 ** This routine only works on a [BLOB handle] which has been created
6528 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6529 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
6530 ** to this routine results in undefined and probably undesirable behavior.
6531 **
6532 ** See also: [sqlite3_blob_write()].
6533 */
6534 SQLITE_API int SQLITE_STDCALL sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
6535 
6536 /*
6537 ** CAPI3REF: Write Data Into A BLOB Incrementally
6538 ** METHOD: sqlite3_blob
6539 **
6540 ** ^(This function is used to write data into an open [BLOB handle] from a
6541 ** caller-supplied buffer. N bytes of data are copied from the buffer Z
6542 ** into the open BLOB, starting at offset iOffset.)^
6543 **
6544 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
6545 ** Otherwise, an [error code] or an [extended error code] is returned.)^
6546 ** ^Unless SQLITE_MISUSE is returned, this function sets the
6547 ** [database connection] error code and message accessible via
6548 ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
6549 **
6550 ** ^If the [BLOB handle] passed as the first argument was not opened for
6551 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
6552 ** this function returns [SQLITE_READONLY].
6553 **
6554 ** This function may only modify the contents of the BLOB; it is
6555 ** not possible to increase the size of a BLOB using this API.
6556 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
6557 ** [SQLITE_ERROR] is returned and no data is written. The size of the
6558 ** BLOB (and hence the maximum value of N+iOffset) can be determined
6559 ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
6560 ** than zero [SQLITE_ERROR] is returned and no data is written.
6561 **
6562 ** ^An attempt to write to an expired [BLOB handle] fails with an
6563 ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
6564 ** before the [BLOB handle] expired are not rolled back by the
6565 ** expiration of the handle, though of course those changes might
6566 ** have been overwritten by the statement that expired the BLOB handle
6567 ** or by other independent statements.
6568 **
6569 ** This routine only works on a [BLOB handle] which has been created
6570 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6571 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
6572 ** to this routine results in undefined and probably undesirable behavior.
6573 **
6574 ** See also: [sqlite3_blob_read()].
6575 */
6576 SQLITE_API int SQLITE_STDCALL sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
6577 
6578 /*
6579 ** CAPI3REF: Virtual File System Objects
6580 **
6581 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
6582 ** that SQLite uses to interact
6583 ** with the underlying operating system. Most SQLite builds come with a
6584 ** single default VFS that is appropriate for the host computer.
6585 ** New VFSes can be registered and existing VFSes can be unregistered.
6586 ** The following interfaces are provided.
6587 **
6588 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
6589 ** ^Names are case sensitive.
6590 ** ^Names are zero-terminated UTF-8 strings.
6591 ** ^If there is no match, a NULL pointer is returned.
6592 ** ^If zVfsName is NULL then the default VFS is returned.
6593 **
6594 ** ^New VFSes are registered with sqlite3_vfs_register().
6595 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
6596 ** ^The same VFS can be registered multiple times without injury.
6597 ** ^To make an existing VFS into the default VFS, register it again
6598 ** with the makeDflt flag set. If two different VFSes with the
6599 ** same name are registered, the behavior is undefined. If a
6600 ** VFS is registered with a name that is NULL or an empty string,
6601 ** then the behavior is undefined.
6602 **
6603 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
6604 ** ^(If the default VFS is unregistered, another VFS is chosen as
6605 ** the default. The choice for the new VFS is arbitrary.)^
6606 */
6607 SQLITE_API sqlite3_vfs *SQLITE_STDCALL sqlite3_vfs_find(const char *zVfsName);
6608 SQLITE_API int SQLITE_STDCALL sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
6609 SQLITE_API int SQLITE_STDCALL sqlite3_vfs_unregister(sqlite3_vfs*);
6610 
6611 /*
6612 ** CAPI3REF: Mutexes
6613 **
6614 ** The SQLite core uses these routines for thread
6615 ** synchronization. Though they are intended for internal
6616 ** use by SQLite, code that links against SQLite is
6617 ** permitted to use any of these routines.
6618 **
6619 ** The SQLite source code contains multiple implementations
6620 ** of these mutex routines. An appropriate implementation
6621 ** is selected automatically at compile-time. The following
6622 ** implementations are available in the SQLite core:
6623 **
6624 ** <ul>
6625 ** <li> SQLITE_MUTEX_PTHREADS
6626 ** <li> SQLITE_MUTEX_W32
6627 ** <li> SQLITE_MUTEX_NOOP
6628 ** </ul>
6629 **
6630 ** The SQLITE_MUTEX_NOOP implementation is a set of routines
6631 ** that does no real locking and is appropriate for use in
6632 ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and
6633 ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
6634 ** and Windows.
6635 **
6636 ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6637 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6638 ** implementation is included with the library. In this case the
6639 ** application must supply a custom mutex implementation using the
6640 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6641 ** before calling sqlite3_initialize() or any other public sqlite3_
6642 ** function that calls sqlite3_initialize().
6643 **
6644 ** ^The sqlite3_mutex_alloc() routine allocates a new
6645 ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
6646 ** routine returns NULL if it is unable to allocate the requested
6647 ** mutex. The argument to sqlite3_mutex_alloc() must one of these
6648 ** integer constants:
6649 **
6650 ** <ul>
6651 ** <li> SQLITE_MUTEX_FAST
6652 ** <li> SQLITE_MUTEX_RECURSIVE
6653 ** <li> SQLITE_MUTEX_STATIC_MASTER
6654 ** <li> SQLITE_MUTEX_STATIC_MEM
6655 ** <li> SQLITE_MUTEX_STATIC_OPEN
6656 ** <li> SQLITE_MUTEX_STATIC_PRNG
6657 ** <li> SQLITE_MUTEX_STATIC_LRU
6658 ** <li> SQLITE_MUTEX_STATIC_PMEM
6659 ** <li> SQLITE_MUTEX_STATIC_APP1
6660 ** <li> SQLITE_MUTEX_STATIC_APP2
6661 ** <li> SQLITE_MUTEX_STATIC_APP3
6662 ** <li> SQLITE_MUTEX_STATIC_VFS1
6663 ** <li> SQLITE_MUTEX_STATIC_VFS2
6664 ** <li> SQLITE_MUTEX_STATIC_VFS3
6665 ** </ul>
6666 **
6667 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
6668 ** cause sqlite3_mutex_alloc() to create
6669 ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6670 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
6671 ** The mutex implementation does not need to make a distinction
6672 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6673 ** not want to. SQLite will only request a recursive mutex in
6674 ** cases where it really needs one. If a faster non-recursive mutex
6675 ** implementation is available on the host platform, the mutex subsystem
6676 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
6677 **
6678 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
6679 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
6680 ** a pointer to a static preexisting mutex. ^Nine static mutexes are
6681 ** used by the current version of SQLite. Future versions of SQLite
6682 ** may add additional static mutexes. Static mutexes are for internal
6683 ** use by SQLite only. Applications that use SQLite mutexes should
6684 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6685 ** SQLITE_MUTEX_RECURSIVE.
6686 **
6687 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6688 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6689 ** returns a different mutex on every call. ^For the static
6690 ** mutex types, the same mutex is returned on every call that has
6691 ** the same type number.
6692 **
6693 ** ^The sqlite3_mutex_free() routine deallocates a previously
6694 ** allocated dynamic mutex. Attempting to deallocate a static
6695 ** mutex results in undefined behavior.
6696 **
6697 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6698 ** to enter a mutex. ^If another thread is already within the mutex,
6699 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6700 ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
6701 ** upon successful entry. ^(Mutexes created using
6702 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6703 ** In such cases, the
6704 ** mutex must be exited an equal number of times before another thread
6705 ** can enter.)^ If the same thread tries to enter any mutex other
6706 ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
6707 **
6708 ** ^(Some systems (for example, Windows 95) do not support the operation
6709 ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
6710 ** will always return SQLITE_BUSY. The SQLite core only ever uses
6711 ** sqlite3_mutex_try() as an optimization so this is acceptable
6712 ** behavior.)^
6713 **
6714 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
6715 ** previously entered by the same thread. The behavior
6716 ** is undefined if the mutex is not currently entered by the
6717 ** calling thread or is not currently allocated.
6718 **
6719 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6720 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6721 ** behave as no-ops.
6722 **
6723 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6724 */
6725 SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_mutex_alloc(int);
6726 SQLITE_API void SQLITE_STDCALL sqlite3_mutex_free(sqlite3_mutex*);
6727 SQLITE_API void SQLITE_STDCALL sqlite3_mutex_enter(sqlite3_mutex*);
6728 SQLITE_API int SQLITE_STDCALL sqlite3_mutex_try(sqlite3_mutex*);
6729 SQLITE_API void SQLITE_STDCALL sqlite3_mutex_leave(sqlite3_mutex*);
6730 
6731 /*
6732 ** CAPI3REF: Mutex Methods Object
6733 **
6734 ** An instance of this structure defines the low-level routines
6735 ** used to allocate and use mutexes.
6736 **
6737 ** Usually, the default mutex implementations provided by SQLite are
6738 ** sufficient, however the application has the option of substituting a custom
6739 ** implementation for specialized deployments or systems for which SQLite
6740 ** does not provide a suitable implementation. In this case, the application
6741 ** creates and populates an instance of this structure to pass
6742 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6743 ** Additionally, an instance of this structure can be used as an
6744 ** output variable when querying the system for the current mutex
6745 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6746 **
6747 ** ^The xMutexInit method defined by this structure is invoked as
6748 ** part of system initialization by the sqlite3_initialize() function.
6749 ** ^The xMutexInit routine is called by SQLite exactly once for each
6750 ** effective call to [sqlite3_initialize()].
6751 **
6752 ** ^The xMutexEnd method defined by this structure is invoked as
6753 ** part of system shutdown by the sqlite3_shutdown() function. The
6754 ** implementation of this method is expected to release all outstanding
6755 ** resources obtained by the mutex methods implementation, especially
6756 ** those obtained by the xMutexInit method. ^The xMutexEnd()
6757 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
6758 **
6759 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
6760 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6761 ** xMutexNotheld) implement the following interfaces (respectively):
6762 **
6763 ** <ul>
6764 ** <li> [sqlite3_mutex_alloc()] </li>
6765 ** <li> [sqlite3_mutex_free()] </li>
6766 ** <li> [sqlite3_mutex_enter()] </li>
6767 ** <li> [sqlite3_mutex_try()] </li>
6768 ** <li> [sqlite3_mutex_leave()] </li>
6769 ** <li> [sqlite3_mutex_held()] </li>
6770 ** <li> [sqlite3_mutex_notheld()] </li>
6771 ** </ul>)^
6772 **
6773 ** The only difference is that the public sqlite3_XXX functions enumerated
6774 ** above silently ignore any invocations that pass a NULL pointer instead
6775 ** of a valid mutex handle. The implementations of the methods defined
6776 ** by this structure are not required to handle this case, the results
6777 ** of passing a NULL pointer instead of a valid mutex handle are undefined
6778 ** (i.e. it is acceptable to provide an implementation that segfaults if
6779 ** it is passed a NULL pointer).
6780 **
6781 ** The xMutexInit() method must be threadsafe. It must be harmless to
6782 ** invoke xMutexInit() multiple times within the same process and without
6783 ** intervening calls to xMutexEnd(). Second and subsequent calls to
6784 ** xMutexInit() must be no-ops.
6785 **
6786 ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
6787 ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory
6788 ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
6789 ** memory allocation for a fast or recursive mutex.
6790 **
6791 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
6792 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
6793 ** If xMutexInit fails in any way, it is expected to clean up after itself
6794 ** prior to returning.
6795 */
6796 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6797 struct sqlite3_mutex_methods {
6798  int (*xMutexInit)(void);
6799  int (*xMutexEnd)(void);
6800  sqlite3_mutex *(*xMutexAlloc)(int);
6801  void (*xMutexFree)(sqlite3_mutex *);
6802  void (*xMutexEnter)(sqlite3_mutex *);
6803  int (*xMutexTry)(sqlite3_mutex *);
6804  void (*xMutexLeave)(sqlite3_mutex *);
6805  int (*xMutexHeld)(sqlite3_mutex *);
6806  int (*xMutexNotheld)(sqlite3_mutex *);
6807 };
6808 
6809 /*
6810 ** CAPI3REF: Mutex Verification Routines
6811 **
6812 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6813 ** are intended for use inside assert() statements. The SQLite core
6814 ** never uses these routines except inside an assert() and applications
6815 ** are advised to follow the lead of the core. The SQLite core only
6816 ** provides implementations for these routines when it is compiled
6817 ** with the SQLITE_DEBUG flag. External mutex implementations
6818 ** are only required to provide these routines if SQLITE_DEBUG is
6819 ** defined and if NDEBUG is not defined.
6820 **
6821 ** These routines should return true if the mutex in their argument
6822 ** is held or not held, respectively, by the calling thread.
6823 **
6824 ** The implementation is not required to provide versions of these
6825 ** routines that actually work. If the implementation does not provide working
6826 ** versions of these routines, it should at least provide stubs that always
6827 ** return true so that one does not get spurious assertion failures.
6828 **
6829 ** If the argument to sqlite3_mutex_held() is a NULL pointer then
6830 ** the routine should return 1. This seems counter-intuitive since
6831 ** clearly the mutex cannot be held if it does not exist. But
6832 ** the reason the mutex does not exist is because the build is not
6833 ** using mutexes. And we do not want the assert() containing the
6834 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
6835 ** the appropriate thing to do. The sqlite3_mutex_notheld()
6836 ** interface should also return 1 when given a NULL pointer.
6837 */
6838 #ifndef NDEBUG
6839 SQLITE_API int SQLITE_STDCALL sqlite3_mutex_held(sqlite3_mutex*);
6840 SQLITE_API int SQLITE_STDCALL sqlite3_mutex_notheld(sqlite3_mutex*);
6841 #endif
6842 
6843 /*
6844 ** CAPI3REF: Mutex Types
6845 **
6846 ** The [sqlite3_mutex_alloc()] interface takes a single argument
6847 ** which is one of these integer constants.
6848 **
6849 ** The set of static mutexes may change from one SQLite release to the
6850 ** next. Applications that override the built-in mutex logic must be
6851 ** prepared to accommodate additional static mutexes.
6852 */
6853 #define SQLITE_MUTEX_FAST 0
6854 #define SQLITE_MUTEX_RECURSIVE 1
6855 #define SQLITE_MUTEX_STATIC_MASTER 2
6856 #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
6857 #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
6858 #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
6859 #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */
6860 #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
6861 #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
6862 #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
6863 #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
6864 #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
6865 #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
6866 #define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */
6867 #define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */
6868 #define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */
6869 
6870 /*
6871 ** CAPI3REF: Retrieve the mutex for a database connection
6872 ** METHOD: sqlite3
6873 **
6874 ** ^This interface returns a pointer the [sqlite3_mutex] object that
6875 ** serializes access to the [database connection] given in the argument
6876 ** when the [threading mode] is Serialized.
6877 ** ^If the [threading mode] is Single-thread or Multi-thread then this
6878 ** routine returns a NULL pointer.
6879 */
6880 SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_db_mutex(sqlite3*);
6881 
6882 /*
6883 ** CAPI3REF: Low-Level Control Of Database Files
6884 ** METHOD: sqlite3
6885 **
6886 ** ^The [sqlite3_file_control()] interface makes a direct call to the
6887 ** xFileControl method for the [sqlite3_io_methods] object associated
6888 ** with a particular database identified by the second argument. ^The
6889 ** name of the database is "main" for the main database or "temp" for the
6890 ** TEMP database, or the name that appears after the AS keyword for
6891 ** databases that are added using the [ATTACH] SQL command.
6892 ** ^A NULL pointer can be used in place of "main" to refer to the
6893 ** main database file.
6894 ** ^The third and fourth parameters to this routine
6895 ** are passed directly through to the second and third parameters of
6896 ** the xFileControl method. ^The return value of the xFileControl
6897 ** method becomes the return value of this routine.
6898 **
6899 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
6900 ** a pointer to the underlying [sqlite3_file] object to be written into
6901 ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
6902 ** case is a short-circuit path which does not actually invoke the
6903 ** underlying sqlite3_io_methods.xFileControl method.
6904 **
6905 ** ^If the second parameter (zDbName) does not match the name of any
6906 ** open database file, then SQLITE_ERROR is returned. ^This error
6907 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
6908 ** or [sqlite3_errmsg()]. The underlying xFileControl method might
6909 ** also return SQLITE_ERROR. There is no way to distinguish between
6910 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6911 ** xFileControl method.
6912 **
6913 ** See also: [SQLITE_FCNTL_LOCKSTATE]
6914 */
6915 SQLITE_API int SQLITE_STDCALL sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6916 
6917 /*
6918 ** CAPI3REF: Testing Interface
6919 **
6920 ** ^The sqlite3_test_control() interface is used to read out internal
6921 ** state of SQLite and to inject faults into SQLite for testing
6922 ** purposes. ^The first parameter is an operation code that determines
6923 ** the number, meaning, and operation of all subsequent parameters.
6924 **
6925 ** This interface is not for use by applications. It exists solely
6926 ** for verifying the correct operation of the SQLite library. Depending
6927 ** on how the SQLite library is compiled, this interface might not exist.
6928 **
6929 ** The details of the operation codes, their meanings, the parameters
6930 ** they take, and what they do are all subject to change without notice.
6931 ** Unlike most of the SQLite API, this function is not guaranteed to
6932 ** operate consistently from one release to the next.
6933 */
6934 SQLITE_API int SQLITE_CDECL sqlite3_test_control(int op, ...);
6935 
6936 /*
6937 ** CAPI3REF: Testing Interface Operation Codes
6938 **
6939 ** These constants are the valid operation code parameters used
6940 ** as the first argument to [sqlite3_test_control()].
6941 **
6942 ** These parameters and their meanings are subject to change
6943 ** without notice. These values are for testing purposes only.
6944 ** Applications should not use any of these parameters or the
6945 ** [sqlite3_test_control()] interface.
6946 */
6947 #define SQLITE_TESTCTRL_FIRST 5
6948 #define SQLITE_TESTCTRL_PRNG_SAVE 5
6949 #define SQLITE_TESTCTRL_PRNG_RESTORE 6
6950 #define SQLITE_TESTCTRL_PRNG_RESET 7
6951 #define SQLITE_TESTCTRL_BITVEC_TEST 8
6952 #define SQLITE_TESTCTRL_FAULT_INSTALL 9
6953 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
6954 #define SQLITE_TESTCTRL_PENDING_BYTE 11
6955 #define SQLITE_TESTCTRL_ASSERT 12
6956 #define SQLITE_TESTCTRL_ALWAYS 13
6957 #define SQLITE_TESTCTRL_RESERVE 14
6958 #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
6959 #define SQLITE_TESTCTRL_ISKEYWORD 16
6960 #define SQLITE_TESTCTRL_SCRATCHMALLOC 17
6961 #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
6962 #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
6963 #define SQLITE_TESTCTRL_NEVER_CORRUPT 20
6964 #define SQLITE_TESTCTRL_VDBE_COVERAGE 21
6965 #define SQLITE_TESTCTRL_BYTEORDER 22
6966 #define SQLITE_TESTCTRL_ISINIT 23
6967 #define SQLITE_TESTCTRL_SORTER_MMAP 24
6968 #define SQLITE_TESTCTRL_IMPOSTER 25
6969 #define SQLITE_TESTCTRL_LAST 25
6970 
6971 /*
6972 ** CAPI3REF: SQLite Runtime Status
6973 **
6974 ** ^These interfaces are used to retrieve runtime status information
6975 ** about the performance of SQLite, and optionally to reset various
6976 ** highwater marks. ^The first argument is an integer code for
6977 ** the specific parameter to measure. ^(Recognized integer codes
6978 ** are of the form [status parameters | SQLITE_STATUS_...].)^
6979 ** ^The current value of the parameter is returned into *pCurrent.
6980 ** ^The highest recorded value is returned in *pHighwater. ^If the
6981 ** resetFlag is true, then the highest record value is reset after
6982 ** *pHighwater is written. ^(Some parameters do not record the highest
6983 ** value. For those parameters
6984 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
6985 ** ^(Other parameters record only the highwater mark and not the current
6986 ** value. For these latter parameters nothing is written into *pCurrent.)^
6987 **
6988 ** ^The sqlite3_status() and sqlite3_status64() routines return
6989 ** SQLITE_OK on success and a non-zero [error code] on failure.
6990 **
6991 ** If either the current value or the highwater mark is too large to
6992 ** be represented by a 32-bit integer, then the values returned by
6993 ** sqlite3_status() are undefined.
6994 **
6995 ** See also: [sqlite3_db_status()]
6996 */
6997 SQLITE_API int SQLITE_STDCALL sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6998 SQLITE_API int SQLITE_STDCALL sqlite3_status64(
6999  int op,
7000  sqlite3_int64 *pCurrent,
7001  sqlite3_int64 *pHighwater,
7002  int resetFlag
7003 );
7004 
7005 
7006 /*
7007 ** CAPI3REF: Status Parameters
7008 ** KEYWORDS: {status parameters}
7009 **
7010 ** These integer constants designate various run-time status parameters
7011 ** that can be returned by [sqlite3_status()].
7012 **
7013 ** <dl>
7014 ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
7015 ** <dd>This parameter is the current amount of memory checked out
7016 ** using [sqlite3_malloc()], either directly or indirectly. The
7017 ** figure includes calls made to [sqlite3_malloc()] by the application
7018 ** and internal memory usage by the SQLite library. Scratch memory
7019 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
7020 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
7021 ** this parameter. The amount returned is the sum of the allocation
7022 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
7023 **
7024 ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
7025 ** <dd>This parameter records the largest memory allocation request
7026 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
7027 ** internal equivalents). Only the value returned in the
7028 ** *pHighwater parameter to [sqlite3_status()] is of interest.
7029 ** The value written into the *pCurrent parameter is undefined.</dd>)^
7030 **
7031 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
7032 ** <dd>This parameter records the number of separate memory allocations
7033 ** currently checked out.</dd>)^
7034 **
7035 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
7036 ** <dd>This parameter returns the number of pages used out of the
7037 ** [pagecache memory allocator] that was configured using
7038 ** [SQLITE_CONFIG_PAGECACHE]. The
7039 ** value returned is in pages, not in bytes.</dd>)^
7040 **
7041 ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
7042 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
7043 ** <dd>This parameter returns the number of bytes of page cache
7044 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
7045 ** buffer and where forced to overflow to [sqlite3_malloc()]. The
7046 ** returned value includes allocations that overflowed because they
7047 ** where too large (they were larger than the "sz" parameter to
7048 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
7049 ** no space was left in the page cache.</dd>)^
7050 **
7051 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
7052 ** <dd>This parameter records the largest memory allocation request
7053 ** handed to [pagecache memory allocator]. Only the value returned in the
7054 ** *pHighwater parameter to [sqlite3_status()] is of interest.
7055 ** The value written into the *pCurrent parameter is undefined.</dd>)^
7056 **
7057 ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
7058 ** <dd>This parameter returns the number of allocations used out of the
7059 ** [scratch memory allocator] configured using
7060 ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
7061 ** in bytes. Since a single thread may only have one scratch allocation
7062 ** outstanding at time, this parameter also reports the number of threads
7063 ** using scratch memory at the same time.</dd>)^
7064 **
7065 ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
7066 ** <dd>This parameter returns the number of bytes of scratch memory
7067 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
7068 ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
7069 ** returned include overflows because the requested allocation was too
7070 ** larger (that is, because the requested allocation was larger than the
7071 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
7072 ** slots were available.
7073 ** </dd>)^
7074 **
7075 ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
7076 ** <dd>This parameter records the largest memory allocation request
7077 ** handed to [scratch memory allocator]. Only the value returned in the
7078 ** *pHighwater parameter to [sqlite3_status()] is of interest.
7079 ** The value written into the *pCurrent parameter is undefined.</dd>)^
7080 **
7081 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
7082 ** <dd>The *pHighwater parameter records the deepest parser stack.
7083 ** The *pCurrent value is undefined. The *pHighwater value is only
7084 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
7085 ** </dl>
7086 **
7087 ** New status parameters may be added from time to time.
7088 */
7089 #define SQLITE_STATUS_MEMORY_USED 0
7090 #define SQLITE_STATUS_PAGECACHE_USED 1
7091 #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
7092 #define SQLITE_STATUS_SCRATCH_USED 3
7093 #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
7094 #define SQLITE_STATUS_MALLOC_SIZE 5
7095 #define SQLITE_STATUS_PARSER_STACK 6
7096 #define SQLITE_STATUS_PAGECACHE_SIZE 7
7097 #define SQLITE_STATUS_SCRATCH_SIZE 8
7098 #define SQLITE_STATUS_MALLOC_COUNT 9
7099 
7100 /*
7101 ** CAPI3REF: Database Connection Status
7102 ** METHOD: sqlite3
7103 **
7104 ** ^This interface is used to retrieve runtime status information
7105 ** about a single [database connection]. ^The first argument is the
7106 ** database connection object to be interrogated. ^The second argument
7107 ** is an integer constant, taken from the set of
7108 ** [SQLITE_DBSTATUS options], that
7109 ** determines the parameter to interrogate. The set of
7110 ** [SQLITE_DBSTATUS options] is likely
7111 ** to grow in future releases of SQLite.
7112 **
7113 ** ^The current value of the requested parameter is written into *pCur
7114 ** and the highest instantaneous value is written into *pHiwtr. ^If
7115 ** the resetFlg is true, then the highest instantaneous value is
7116 ** reset back down to the current value.
7117 **
7118 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
7119 ** non-zero [error code] on failure.
7120 **
7121 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
7122 */
7123 SQLITE_API int SQLITE_STDCALL sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
7124 
7125 /*
7126 ** CAPI3REF: Status Parameters for database connections
7127 ** KEYWORDS: {SQLITE_DBSTATUS options}
7128 **
7129 ** These constants are the available integer "verbs" that can be passed as
7130 ** the second argument to the [sqlite3_db_status()] interface.
7131 **
7132 ** New verbs may be added in future releases of SQLite. Existing verbs
7133 ** might be discontinued. Applications should check the return code from
7134 ** [sqlite3_db_status()] to make sure that the call worked.
7135 ** The [sqlite3_db_status()] interface will return a non-zero error code
7136 ** if a discontinued or unsupported verb is invoked.
7137 **
7138 ** <dl>
7139 ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
7140 ** <dd>This parameter returns the number of lookaside memory slots currently
7141 ** checked out.</dd>)^
7142 **
7143 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
7144 ** <dd>This parameter returns the number malloc attempts that were
7145 ** satisfied using lookaside memory. Only the high-water value is meaningful;
7146 ** the current value is always zero.)^
7147 **
7148 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
7149 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
7150 ** <dd>This parameter returns the number malloc attempts that might have
7151 ** been satisfied using lookaside memory but failed due to the amount of
7152 ** memory requested being larger than the lookaside slot size.
7153 ** Only the high-water value is meaningful;
7154 ** the current value is always zero.)^
7155 **
7156 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
7157 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
7158 ** <dd>This parameter returns the number malloc attempts that might have
7159 ** been satisfied using lookaside memory but failed due to all lookaside
7160 ** memory already being in use.
7161 ** Only the high-water value is meaningful;
7162 ** the current value is always zero.)^
7163 **
7164 ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
7165 ** <dd>This parameter returns the approximate number of bytes of heap
7166 ** memory used by all pager caches associated with the database connection.)^
7167 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
7168 **
7169 ** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]
7170 ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
7171 ** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
7172 ** pager cache is shared between two or more connections the bytes of heap
7173 ** memory used by that pager cache is divided evenly between the attached
7174 ** connections.)^ In other words, if none of the pager caches associated
7175 ** with the database connection are shared, this request returns the same
7176 ** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are
7177 ** shared, the value returned by this call will be smaller than that returned
7178 ** by DBSTATUS_CACHE_USED. ^The highwater mark associated with
7179 ** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.
7180 **
7181 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
7182 ** <dd>This parameter returns the approximate number of bytes of heap
7183 ** memory used to store the schema for all databases associated
7184 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
7185 ** ^The full amount of memory used by the schemas is reported, even if the
7186 ** schema memory is shared with other database connections due to
7187 ** [shared cache mode] being enabled.
7188 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
7189 **
7190 ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
7191 ** <dd>This parameter returns the approximate number of bytes of heap
7192 ** and lookaside memory used by all prepared statements associated with
7193 ** the database connection.)^
7194 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
7195 ** </dd>
7196 **
7197 ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
7198 ** <dd>This parameter returns the number of pager cache hits that have
7199 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
7200 ** is always 0.
7201 ** </dd>
7202 **
7203 ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
7204 ** <dd>This parameter returns the number of pager cache misses that have
7205 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
7206 ** is always 0.
7207 ** </dd>
7208 **
7209 ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
7210 ** <dd>This parameter returns the number of dirty cache entries that have
7211 ** been written to disk. Specifically, the number of pages written to the
7212 ** wal file in wal mode databases, or the number of pages written to the
7213 ** database file in rollback mode databases. Any pages written as part of
7214 ** transaction rollback or database recovery operations are not included.
7215 ** If an IO or other error occurs while writing a page to disk, the effect
7216 ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
7217 ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
7218 ** </dd>
7219 **
7220 ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
7221 ** <dd>This parameter returns zero for the current value if and only if
7222 ** all foreign key constraints (deferred or immediate) have been
7223 ** resolved.)^ ^The highwater mark is always 0.
7224 ** </dd>
7225 ** </dl>
7226 */
7227 #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
7228 #define SQLITE_DBSTATUS_CACHE_USED 1
7229 #define SQLITE_DBSTATUS_SCHEMA_USED 2
7230 #define SQLITE_DBSTATUS_STMT_USED 3
7231 #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
7232 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
7233 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
7234 #define SQLITE_DBSTATUS_CACHE_HIT 7
7235 #define SQLITE_DBSTATUS_CACHE_MISS 8
7236 #define SQLITE_DBSTATUS_CACHE_WRITE 9
7237 #define SQLITE_DBSTATUS_DEFERRED_FKS 10
7238 #define SQLITE_DBSTATUS_CACHE_USED_SHARED 11
7239 #define SQLITE_DBSTATUS_MAX 11 /* Largest defined DBSTATUS */
7240 
7241 
7242 /*
7243 ** CAPI3REF: Prepared Statement Status
7244 ** METHOD: sqlite3_stmt
7245 **
7246 ** ^(Each prepared statement maintains various
7247 ** [SQLITE_STMTSTATUS counters] that measure the number
7248 ** of times it has performed specific operations.)^ These counters can
7249 ** be used to monitor the performance characteristics of the prepared
7250 ** statements. For example, if the number of table steps greatly exceeds
7251 ** the number of table searches or result rows, that would tend to indicate
7252 ** that the prepared statement is using a full table scan rather than
7253 ** an index.
7254 **
7255 ** ^(This interface is used to retrieve and reset counter values from
7256 ** a [prepared statement]. The first argument is the prepared statement
7257 ** object to be interrogated. The second argument
7258 ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
7259 ** to be interrogated.)^
7260 ** ^The current value of the requested counter is returned.
7261 ** ^If the resetFlg is true, then the counter is reset to zero after this
7262 ** interface call returns.
7263 **
7264 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
7265 */
7266 SQLITE_API int SQLITE_STDCALL sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
7267 
7268 /*
7269 ** CAPI3REF: Status Parameters for prepared statements
7270 ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
7271 **
7272 ** These preprocessor macros define integer codes that name counter
7273 ** values associated with the [sqlite3_stmt_status()] interface.
7274 ** The meanings of the various counters are as follows:
7275 **
7276 ** <dl>
7277 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
7278 ** <dd>^This is the number of times that SQLite has stepped forward in
7279 ** a table as part of a full table scan. Large numbers for this counter
7280 ** may indicate opportunities for performance improvement through
7281 ** careful use of indices.</dd>
7282 **
7283 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
7284 ** <dd>^This is the number of sort operations that have occurred.
7285 ** A non-zero value in this counter may indicate an opportunity to
7286 ** improvement performance through careful use of indices.</dd>
7287 **
7288 ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
7289 ** <dd>^This is the number of rows inserted into transient indices that
7290 ** were created automatically in order to help joins run faster.
7291 ** A non-zero value in this counter may indicate an opportunity to
7292 ** improvement performance by adding permanent indices that do not
7293 ** need to be reinitialized each time the statement is run.</dd>
7294 **
7295 ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
7296 ** <dd>^This is the number of virtual machine operations executed
7297 ** by the prepared statement if that number is less than or equal
7298 ** to 2147483647. The number of virtual machine operations can be
7299 ** used as a proxy for the total work done by the prepared statement.
7300 ** If the number of virtual machine operations exceeds 2147483647
7301 ** then the value returned by this statement status code is undefined.
7302 ** </dd>
7303 ** </dl>
7304 */
7305 #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
7306 #define SQLITE_STMTSTATUS_SORT 2
7307 #define SQLITE_STMTSTATUS_AUTOINDEX 3
7308 #define SQLITE_STMTSTATUS_VM_STEP 4
7309 
7310 /*
7311 ** CAPI3REF: Custom Page Cache Object
7312 **
7313 ** The sqlite3_pcache type is opaque. It is implemented by
7314 ** the pluggable module. The SQLite core has no knowledge of
7315 ** its size or internal structure and never deals with the
7316 ** sqlite3_pcache object except by holding and passing pointers
7317 ** to the object.
7318 **
7319 ** See [sqlite3_pcache_methods2] for additional information.
7320 */
7321 typedef struct sqlite3_pcache sqlite3_pcache;
7322 
7323 /*
7324 ** CAPI3REF: Custom Page Cache Object
7325 **
7326 ** The sqlite3_pcache_page object represents a single page in the
7327 ** page cache. The page cache will allocate instances of this
7328 ** object. Various methods of the page cache use pointers to instances
7329 ** of this object as parameters or as their return value.
7330 **
7331 ** See [sqlite3_pcache_methods2] for additional information.
7332 */
7333 typedef struct sqlite3_pcache_page sqlite3_pcache_page;
7334 struct sqlite3_pcache_page {
7335  void *pBuf; /* The content of the page */
7336  void *pExtra; /* Extra information associated with the page */
7337 };
7338 
7339 /*
7340 ** CAPI3REF: Application Defined Page Cache.
7341 ** KEYWORDS: {page cache}
7342 **
7343 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
7344 ** register an alternative page cache implementation by passing in an
7345 ** instance of the sqlite3_pcache_methods2 structure.)^
7346 ** In many applications, most of the heap memory allocated by
7347 ** SQLite is used for the page cache.
7348 ** By implementing a
7349 ** custom page cache using this API, an application can better control
7350 ** the amount of memory consumed by SQLite, the way in which
7351 ** that memory is allocated and released, and the policies used to
7352 ** determine exactly which parts of a database file are cached and for
7353 ** how long.
7354 **
7355 ** The alternative page cache mechanism is an
7356 ** extreme measure that is only needed by the most demanding applications.
7357 ** The built-in page cache is recommended for most uses.
7358 **
7359 ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
7360 ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
7361 ** the application may discard the parameter after the call to
7362 ** [sqlite3_config()] returns.)^
7363 **
7364 ** [[the xInit() page cache method]]
7365 ** ^(The xInit() method is called once for each effective
7366 ** call to [sqlite3_initialize()])^
7367 ** (usually only once during the lifetime of the process). ^(The xInit()
7368 ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
7369 ** The intent of the xInit() method is to set up global data structures
7370 ** required by the custom page cache implementation.
7371 ** ^(If the xInit() method is NULL, then the
7372 ** built-in default page cache is used instead of the application defined
7373 ** page cache.)^
7374 **
7375 ** [[the xShutdown() page cache method]]
7376 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
7377 ** It can be used to clean up
7378 ** any outstanding resources before process shutdown, if required.
7379 ** ^The xShutdown() method may be NULL.
7380 **
7381 ** ^SQLite automatically serializes calls to the xInit method,
7382 ** so the xInit method need not be threadsafe. ^The
7383 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
7384 ** not need to be threadsafe either. All other methods must be threadsafe
7385 ** in multithreaded applications.
7386 **
7387 ** ^SQLite will never invoke xInit() more than once without an intervening
7388 ** call to xShutdown().
7389 **
7390 ** [[the xCreate() page cache methods]]
7391 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
7392 ** SQLite will typically create one cache instance for each open database file,
7393 ** though this is not guaranteed. ^The
7394 ** first parameter, szPage, is the size in bytes of the pages that must
7395 ** be allocated by the cache. ^szPage will always a power of two. ^The
7396 ** second parameter szExtra is a number of bytes of extra storage
7397 ** associated with each page cache entry. ^The szExtra parameter will
7398 ** a number less than 250. SQLite will use the
7399 ** extra szExtra bytes on each page to store metadata about the underlying
7400 ** database page on disk. The value passed into szExtra depends
7401 ** on the SQLite version, the target platform, and how SQLite was compiled.
7402 ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
7403 ** created will be used to cache database pages of a file stored on disk, or
7404 ** false if it is used for an in-memory database. The cache implementation
7405 ** does not have to do anything special based with the value of bPurgeable;
7406 ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
7407 ** never invoke xUnpin() except to deliberately delete a page.
7408 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
7409 ** false will always have the "discard" flag set to true.
7410 ** ^Hence, a cache created with bPurgeable false will
7411 ** never contain any unpinned pages.
7412 **
7413 ** [[the xCachesize() page cache method]]
7414 ** ^(The xCachesize() method may be called at any time by SQLite to set the
7415 ** suggested maximum cache-size (number of pages stored by) the cache
7416 ** instance passed as the first argument. This is the value configured using
7417 ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
7418 ** parameter, the implementation is not required to do anything with this
7419 ** value; it is advisory only.
7420 **
7421 ** [[the xPagecount() page cache methods]]
7422 ** The xPagecount() method must return the number of pages currently
7423 ** stored in the cache, both pinned and unpinned.
7424 **
7425 ** [[the xFetch() page cache methods]]
7426 ** The xFetch() method locates a page in the cache and returns a pointer to
7427 ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
7428 ** The pBuf element of the returned sqlite3_pcache_page object will be a
7429 ** pointer to a buffer of szPage bytes used to store the content of a
7430 ** single database page. The pExtra element of sqlite3_pcache_page will be
7431 ** a pointer to the szExtra bytes of extra storage that SQLite has requested
7432 ** for each entry in the page cache.
7433 **
7434 ** The page to be fetched is determined by the key. ^The minimum key value
7435 ** is 1. After it has been retrieved using xFetch, the page is considered
7436 ** to be "pinned".
7437 **
7438 ** If the requested page is already in the page cache, then the page cache
7439 ** implementation must return a pointer to the page buffer with its content
7440 ** intact. If the requested page is not already in the cache, then the
7441 ** cache implementation should use the value of the createFlag
7442 ** parameter to help it determined what action to take:
7443 **
7444 ** <table border=1 width=85% align=center>
7445 ** <tr><th> createFlag <th> Behavior when page is not already in cache
7446 ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
7447 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
7448 ** Otherwise return NULL.
7449 ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
7450 ** NULL if allocating a new page is effectively impossible.
7451 ** </table>
7452 **
7453 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
7454 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
7455 ** failed.)^ In between the to xFetch() calls, SQLite may
7456 ** attempt to unpin one or more cache pages by spilling the content of
7457 ** pinned pages to disk and synching the operating system disk cache.
7458 **
7459 ** [[the xUnpin() page cache method]]
7460 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
7461 ** as its second argument. If the third parameter, discard, is non-zero,
7462 ** then the page must be evicted from the cache.
7463 ** ^If the discard parameter is
7464 ** zero, then the page may be discarded or retained at the discretion of
7465 ** page cache implementation. ^The page cache implementation
7466 ** may choose to evict unpinned pages at any time.
7467 **
7468 ** The cache must not perform any reference counting. A single
7469 ** call to xUnpin() unpins the page regardless of the number of prior calls
7470 ** to xFetch().
7471 **
7472 ** [[the xRekey() page cache methods]]
7473 ** The xRekey() method is used to change the key value associated with the
7474 ** page passed as the second argument. If the cache
7475 ** previously contains an entry associated with newKey, it must be
7476 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
7477 ** to be pinned.
7478 **
7479 ** When SQLite calls the xTruncate() method, the cache must discard all
7480 ** existing cache entries with page numbers (keys) greater than or equal
7481 ** to the value of the iLimit parameter passed to xTruncate(). If any
7482 ** of these pages are pinned, they are implicitly unpinned, meaning that
7483 ** they can be safely discarded.
7484 **
7485 ** [[the xDestroy() page cache method]]
7486 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
7487 ** All resources associated with the specified cache should be freed. ^After
7488 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
7489 ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
7490 ** functions.
7491 **
7492 ** [[the xShrink() page cache method]]
7493 ** ^SQLite invokes the xShrink() method when it wants the page cache to
7494 ** free up as much of heap memory as possible. The page cache implementation
7495 ** is not obligated to free any memory, but well-behaved implementations should
7496 ** do their best.
7497 */
7498 typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
7499 struct sqlite3_pcache_methods2 {
7500  int iVersion;
7501  void *pArg;
7502  int (*xInit)(void*);
7503  void (*xShutdown)(void*);
7504  sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
7505  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7506  int (*xPagecount)(sqlite3_pcache*);
7507  sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7508  void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
7509  void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
7510  unsigned oldKey, unsigned newKey);
7511  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7512  void (*xDestroy)(sqlite3_pcache*);
7513  void (*xShrink)(sqlite3_pcache*);
7514 };
7515 
7516 /*
7517 ** This is the obsolete pcache_methods object that has now been replaced
7518 ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
7519 ** retained in the header file for backwards compatibility only.
7520 */
7521 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
7522 struct sqlite3_pcache_methods {
7523  void *pArg;
7524  int (*xInit)(void*);
7525  void (*xShutdown)(void*);
7526  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
7527  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7528  int (*xPagecount)(sqlite3_pcache*);
7529  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7530  void (*xUnpin)(sqlite3_pcache*, void*, int discard);
7531  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
7532  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7533  void (*xDestroy)(sqlite3_pcache*);
7534 };
7535 
7536 
7537 /*
7538 ** CAPI3REF: Online Backup Object
7539 **
7540 ** The sqlite3_backup object records state information about an ongoing
7541 ** online backup operation. ^The sqlite3_backup object is created by
7542 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
7543 ** [sqlite3_backup_finish()].
7544 **
7545 ** See Also: [Using the SQLite Online Backup API]
7546 */
7547 typedef struct sqlite3_backup sqlite3_backup;
7548 
7549 /*
7550 ** CAPI3REF: Online Backup API.
7551 **
7552 ** The backup API copies the content of one database into another.
7553 ** It is useful either for creating backups of databases or
7554 ** for copying in-memory databases to or from persistent files.
7555 **
7556 ** See Also: [Using the SQLite Online Backup API]
7557 **
7558 ** ^SQLite holds a write transaction open on the destination database file
7559 ** for the duration of the backup operation.
7560 ** ^The source database is read-locked only while it is being read;
7561 ** it is not locked continuously for the entire backup operation.
7562 ** ^Thus, the backup may be performed on a live source database without
7563 ** preventing other database connections from
7564 ** reading or writing to the source database while the backup is underway.
7565 **
7566 ** ^(To perform a backup operation:
7567 ** <ol>
7568 ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
7569 ** backup,
7570 ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
7571 ** the data between the two databases, and finally
7572 ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
7573 ** associated with the backup operation.
7574 ** </ol>)^
7575 ** There should be exactly one call to sqlite3_backup_finish() for each
7576 ** successful call to sqlite3_backup_init().
7577 **
7578 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
7579 **
7580 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
7581 ** [database connection] associated with the destination database
7582 ** and the database name, respectively.
7583 ** ^The database name is "main" for the main database, "temp" for the
7584 ** temporary database, or the name specified after the AS keyword in
7585 ** an [ATTACH] statement for an attached database.
7586 ** ^The S and M arguments passed to
7587 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
7588 ** and database name of the source database, respectively.
7589 ** ^The source and destination [database connections] (parameters S and D)
7590 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
7591 ** an error.
7592 **
7593 ** ^A call to sqlite3_backup_init() will fail, returning NULL, if
7594 ** there is already a read or read-write transaction open on the
7595 ** destination database.
7596 **
7597 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
7598 ** returned and an error code and error message are stored in the
7599 ** destination [database connection] D.
7600 ** ^The error code and message for the failed call to sqlite3_backup_init()
7601 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
7602 ** [sqlite3_errmsg16()] functions.
7603 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
7604 ** [sqlite3_backup] object.
7605 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
7606 ** sqlite3_backup_finish() functions to perform the specified backup
7607 ** operation.
7608 **
7609 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
7610 **
7611 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
7612 ** the source and destination databases specified by [sqlite3_backup] object B.
7613 ** ^If N is negative, all remaining source pages are copied.
7614 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
7615 ** are still more pages to be copied, then the function returns [SQLITE_OK].
7616 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
7617 ** from source to destination, then it returns [SQLITE_DONE].
7618 ** ^If an error occurs while running sqlite3_backup_step(B,N),
7619 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
7620 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
7621 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
7622 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
7623 **
7624 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
7625 ** <ol>
7626 ** <li> the destination database was opened read-only, or
7627 ** <li> the destination database is using write-ahead-log journaling
7628 ** and the destination and source page sizes differ, or
7629 ** <li> the destination database is an in-memory database and the
7630 ** destination and source page sizes differ.
7631 ** </ol>)^
7632 **
7633 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
7634 ** the [sqlite3_busy_handler | busy-handler function]
7635 ** is invoked (if one is specified). ^If the
7636 ** busy-handler returns non-zero before the lock is available, then
7637 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
7638 ** sqlite3_backup_step() can be retried later. ^If the source
7639 ** [database connection]
7640 ** is being used to write to the source database when sqlite3_backup_step()
7641 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
7642 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
7643 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
7644 ** [SQLITE_READONLY] is returned, then
7645 ** there is no point in retrying the call to sqlite3_backup_step(). These
7646 ** errors are considered fatal.)^ The application must accept
7647 ** that the backup operation has failed and pass the backup operation handle
7648 ** to the sqlite3_backup_finish() to release associated resources.
7649 **
7650 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
7651 ** on the destination file. ^The exclusive lock is not released until either
7652 ** sqlite3_backup_finish() is called or the backup operation is complete
7653 ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
7654 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
7655 ** lasts for the duration of the sqlite3_backup_step() call.
7656 ** ^Because the source database is not locked between calls to
7657 ** sqlite3_backup_step(), the source database may be modified mid-way
7658 ** through the backup process. ^If the source database is modified by an
7659 ** external process or via a database connection other than the one being
7660 ** used by the backup operation, then the backup will be automatically
7661 ** restarted by the next call to sqlite3_backup_step(). ^If the source
7662 ** database is modified by the using the same database connection as is used
7663 ** by the backup operation, then the backup database is automatically
7664 ** updated at the same time.
7665 **
7666 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
7667 **
7668 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
7669 ** application wishes to abandon the backup operation, the application
7670 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
7671 ** ^The sqlite3_backup_finish() interfaces releases all
7672 ** resources associated with the [sqlite3_backup] object.
7673 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
7674 ** active write-transaction on the destination database is rolled back.
7675 ** The [sqlite3_backup] object is invalid
7676 ** and may not be used following a call to sqlite3_backup_finish().
7677 **
7678 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
7679 ** sqlite3_backup_step() errors occurred, regardless or whether or not
7680 ** sqlite3_backup_step() completed.
7681 ** ^If an out-of-memory condition or IO error occurred during any prior
7682 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
7683 ** sqlite3_backup_finish() returns the corresponding [error code].
7684 **
7685 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
7686 ** is not a permanent error and does not affect the return value of
7687 ** sqlite3_backup_finish().
7688 **
7689 ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
7690 ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
7691 **
7692 ** ^The sqlite3_backup_remaining() routine returns the number of pages still
7693 ** to be backed up at the conclusion of the most recent sqlite3_backup_step().
7694 ** ^The sqlite3_backup_pagecount() routine returns the total number of pages
7695 ** in the source database at the conclusion of the most recent
7696 ** sqlite3_backup_step().
7697 ** ^(The values returned by these functions are only updated by
7698 ** sqlite3_backup_step(). If the source database is modified in a way that
7699 ** changes the size of the source database or the number of pages remaining,
7700 ** those changes are not reflected in the output of sqlite3_backup_pagecount()
7701 ** and sqlite3_backup_remaining() until after the next
7702 ** sqlite3_backup_step().)^
7703 **
7704 ** <b>Concurrent Usage of Database Handles</b>
7705 **
7706 ** ^The source [database connection] may be used by the application for other
7707 ** purposes while a backup operation is underway or being initialized.
7708 ** ^If SQLite is compiled and configured to support threadsafe database
7709 ** connections, then the source database connection may be used concurrently
7710 ** from within other threads.
7711 **
7712 ** However, the application must guarantee that the destination
7713 ** [database connection] is not passed to any other API (by any thread) after
7714 ** sqlite3_backup_init() is called and before the corresponding call to
7715 ** sqlite3_backup_finish(). SQLite does not currently check to see
7716 ** if the application incorrectly accesses the destination [database connection]
7717 ** and so no error code is reported, but the operations may malfunction
7718 ** nevertheless. Use of the destination database connection while a
7719 ** backup is in progress might also also cause a mutex deadlock.
7720 **
7721 ** If running in [shared cache mode], the application must
7722 ** guarantee that the shared cache used by the destination database
7723 ** is not accessed while the backup is running. In practice this means
7724 ** that the application must guarantee that the disk file being
7725 ** backed up to is not accessed by any connection within the process,
7726 ** not just the specific connection that was passed to sqlite3_backup_init().
7727 **
7728 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
7729 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
7730 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
7731 ** APIs are not strictly speaking threadsafe. If they are invoked at the
7732 ** same time as another thread is invoking sqlite3_backup_step() it is
7733 ** possible that they return invalid values.
7734 */
7735 SQLITE_API sqlite3_backup *SQLITE_STDCALL sqlite3_backup_init(
7736  sqlite3 *pDest, /* Destination database handle */
7737  const char *zDestName, /* Destination database name */
7738  sqlite3 *pSource, /* Source database handle */
7739  const char *zSourceName /* Source database name */
7740 );
7741 SQLITE_API int SQLITE_STDCALL sqlite3_backup_step(sqlite3_backup *p, int nPage);
7742 SQLITE_API int SQLITE_STDCALL sqlite3_backup_finish(sqlite3_backup *p);
7743 SQLITE_API int SQLITE_STDCALL sqlite3_backup_remaining(sqlite3_backup *p);
7744 SQLITE_API int SQLITE_STDCALL sqlite3_backup_pagecount(sqlite3_backup *p);
7745 
7746 /*
7747 ** CAPI3REF: Unlock Notification
7748 ** METHOD: sqlite3
7749 **
7750 ** ^When running in shared-cache mode, a database operation may fail with
7751 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
7752 ** individual tables within the shared-cache cannot be obtained. See
7753 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
7754 ** ^This API may be used to register a callback that SQLite will invoke
7755 ** when the connection currently holding the required lock relinquishes it.
7756 ** ^This API is only available if the library was compiled with the
7757 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
7758 **
7759 ** See Also: [Using the SQLite Unlock Notification Feature].
7760 **
7761 ** ^Shared-cache locks are released when a database connection concludes
7762 ** its current transaction, either by committing it or rolling it back.
7763 **
7764 ** ^When a connection (known as the blocked connection) fails to obtain a
7765 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
7766 ** identity of the database connection (the blocking connection) that
7767 ** has locked the required resource is stored internally. ^After an
7768 ** application receives an SQLITE_LOCKED error, it may call the
7769 ** sqlite3_unlock_notify() method with the blocked connection handle as
7770 ** the first argument to register for a callback that will be invoked
7771 ** when the blocking connections current transaction is concluded. ^The
7772 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
7773 ** call that concludes the blocking connections transaction.
7774 **
7775 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
7776 ** there is a chance that the blocking connection will have already
7777 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
7778 ** If this happens, then the specified callback is invoked immediately,
7779 ** from within the call to sqlite3_unlock_notify().)^
7780 **
7781 ** ^If the blocked connection is attempting to obtain a write-lock on a
7782 ** shared-cache table, and more than one other connection currently holds
7783 ** a read-lock on the same table, then SQLite arbitrarily selects one of
7784 ** the other connections to use as the blocking connection.
7785 **
7786 ** ^(There may be at most one unlock-notify callback registered by a
7787 ** blocked connection. If sqlite3_unlock_notify() is called when the
7788 ** blocked connection already has a registered unlock-notify callback,
7789 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
7790 ** called with a NULL pointer as its second argument, then any existing
7791 ** unlock-notify callback is canceled. ^The blocked connections
7792 ** unlock-notify callback may also be canceled by closing the blocked
7793 ** connection using [sqlite3_close()].
7794 **
7795 ** The unlock-notify callback is not reentrant. If an application invokes
7796 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
7797 ** crash or deadlock may be the result.
7798 **
7799 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
7800 ** returns SQLITE_OK.
7801 **
7802 ** <b>Callback Invocation Details</b>
7803 **
7804 ** When an unlock-notify callback is registered, the application provides a
7805 ** single void* pointer that is passed to the callback when it is invoked.
7806 ** However, the signature of the callback function allows SQLite to pass
7807 ** it an array of void* context pointers. The first argument passed to
7808 ** an unlock-notify callback is a pointer to an array of void* pointers,
7809 ** and the second is the number of entries in the array.
7810 **
7811 ** When a blocking connections transaction is concluded, there may be
7812 ** more than one blocked connection that has registered for an unlock-notify
7813 ** callback. ^If two or more such blocked connections have specified the
7814 ** same callback function, then instead of invoking the callback function
7815 ** multiple times, it is invoked once with the set of void* context pointers
7816 ** specified by the blocked connections bundled together into an array.
7817 ** This gives the application an opportunity to prioritize any actions
7818 ** related to the set of unblocked database connections.
7819 **
7820 ** <b>Deadlock Detection</b>
7821 **
7822 ** Assuming that after registering for an unlock-notify callback a
7823 ** database waits for the callback to be issued before taking any further
7824 ** action (a reasonable assumption), then using this API may cause the
7825 ** application to deadlock. For example, if connection X is waiting for
7826 ** connection Y's transaction to be concluded, and similarly connection
7827 ** Y is waiting on connection X's transaction, then neither connection
7828 ** will proceed and the system may remain deadlocked indefinitely.
7829 **
7830 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
7831 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
7832 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
7833 ** unlock-notify callback is registered. The system is said to be in
7834 ** a deadlocked state if connection A has registered for an unlock-notify
7835 ** callback on the conclusion of connection B's transaction, and connection
7836 ** B has itself registered for an unlock-notify callback when connection
7837 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
7838 ** the system is also considered to be deadlocked if connection B has
7839 ** registered for an unlock-notify callback on the conclusion of connection
7840 ** C's transaction, where connection C is waiting on connection A. ^Any
7841 ** number of levels of indirection are allowed.
7842 **
7843 ** <b>The "DROP TABLE" Exception</b>
7844 **
7845 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
7846 ** always appropriate to call sqlite3_unlock_notify(). There is however,
7847 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
7848 ** SQLite checks if there are any currently executing SELECT statements
7849 ** that belong to the same connection. If there are, SQLITE_LOCKED is
7850 ** returned. In this case there is no "blocking connection", so invoking
7851 ** sqlite3_unlock_notify() results in the unlock-notify callback being
7852 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
7853 ** or "DROP INDEX" query, an infinite loop might be the result.
7854 **
7855 ** One way around this problem is to check the extended error code returned
7856 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
7857 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
7858 ** the special "DROP TABLE/INDEX" case, the extended error code is just
7859 ** SQLITE_LOCKED.)^
7860 */
7861 SQLITE_API int SQLITE_STDCALL sqlite3_unlock_notify(
7862  sqlite3 *pBlocked, /* Waiting connection */
7863  void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
7864  void *pNotifyArg /* Argument to pass to xNotify */
7865 );
7866 
7867 
7868 /*
7869 ** CAPI3REF: String Comparison
7870 **
7871 ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
7872 ** and extensions to compare the contents of two buffers containing UTF-8
7873 ** strings in a case-independent fashion, using the same definition of "case
7874 ** independence" that SQLite uses internally when comparing identifiers.
7875 */
7876 SQLITE_API int SQLITE_STDCALL sqlite3_stricmp(const char *, const char *);
7877 SQLITE_API int SQLITE_STDCALL sqlite3_strnicmp(const char *, const char *, int);
7878 
7879 /*
7880 ** CAPI3REF: String Globbing
7881 *
7882 ** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
7883 ** string X matches the [GLOB] pattern P.
7884 ** ^The definition of [GLOB] pattern matching used in
7885 ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
7886 ** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function
7887 ** is case sensitive.
7888 **
7889 ** Note that this routine returns zero on a match and non-zero if the strings
7890 ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
7891 **
7892 ** See also: [sqlite3_strlike()].
7893 */
7894 SQLITE_API int SQLITE_STDCALL sqlite3_strglob(const char *zGlob, const char *zStr);
7895 
7896 /*
7897 ** CAPI3REF: String LIKE Matching
7898 *
7899 ** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
7900 ** string X matches the [LIKE] pattern P with escape character E.
7901 ** ^The definition of [LIKE] pattern matching used in
7902 ** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
7903 ** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without
7904 ** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
7905 ** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
7906 ** insensitive - equivalent upper and lower case ASCII characters match
7907 ** one another.
7908 **
7909 ** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
7910 ** only ASCII characters are case folded.
7911 **
7912 ** Note that this routine returns zero on a match and non-zero if the strings
7913 ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
7914 **
7915 ** See also: [sqlite3_strglob()].
7916 */
7917 SQLITE_API int SQLITE_STDCALL sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
7918 
7919 /*
7920 ** CAPI3REF: Error Logging Interface
7921 **
7922 ** ^The [sqlite3_log()] interface writes a message into the [error log]
7923 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
7924 ** ^If logging is enabled, the zFormat string and subsequent arguments are
7925 ** used with [sqlite3_snprintf()] to generate the final output string.
7926 **
7927 ** The sqlite3_log() interface is intended for use by extensions such as
7928 ** virtual tables, collating functions, and SQL functions. While there is
7929 ** nothing to prevent an application from calling sqlite3_log(), doing so
7930 ** is considered bad form.
7931 **
7932 ** The zFormat string must not be NULL.
7933 **
7934 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
7935 ** will not use dynamically allocated memory. The log message is stored in
7936 ** a fixed-length buffer on the stack. If the log message is longer than
7937 ** a few hundred characters, it will be truncated to the length of the
7938 ** buffer.
7939 */
7940 SQLITE_API void SQLITE_CDECL sqlite3_log(int iErrCode, const char *zFormat, ...);
7941 
7942 /*
7943 ** CAPI3REF: Write-Ahead Log Commit Hook
7944 ** METHOD: sqlite3
7945 **
7946 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
7947 ** is invoked each time data is committed to a database in wal mode.
7948 **
7949 ** ^(The callback is invoked by SQLite after the commit has taken place and
7950 ** the associated write-lock on the database released)^, so the implementation
7951 ** may read, write or [checkpoint] the database as required.
7952 **
7953 ** ^The first parameter passed to the callback function when it is invoked
7954 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
7955 ** registering the callback. ^The second is a copy of the database handle.
7956 ** ^The third parameter is the name of the database that was written to -
7957 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
7958 ** is the number of pages currently in the write-ahead log file,
7959 ** including those that were just committed.
7960 **
7961 ** The callback function should normally return [SQLITE_OK]. ^If an error
7962 ** code is returned, that error will propagate back up through the
7963 ** SQLite code base to cause the statement that provoked the callback
7964 ** to report an error, though the commit will have still occurred. If the
7965 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
7966 ** that does not correspond to any valid SQLite error code, the results
7967 ** are undefined.
7968 **
7969 ** A single database handle may have at most a single write-ahead log callback
7970 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
7971 ** previously registered write-ahead log callback. ^Note that the
7972 ** [sqlite3_wal_autocheckpoint()] interface and the
7973 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
7974 ** overwrite any prior [sqlite3_wal_hook()] settings.
7975 */
7976 SQLITE_API void *SQLITE_STDCALL sqlite3_wal_hook(
7977  sqlite3*,
7978  int(*)(void *,sqlite3*,const char*,int),
7979  void*
7980 );
7981 
7982 /*
7983 ** CAPI3REF: Configure an auto-checkpoint
7984 ** METHOD: sqlite3
7985 **
7986 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
7987 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
7988 ** to automatically [checkpoint]
7989 ** after committing a transaction if there are N or
7990 ** more frames in the [write-ahead log] file. ^Passing zero or
7991 ** a negative value as the nFrame parameter disables automatic
7992 ** checkpoints entirely.
7993 **
7994 ** ^The callback registered by this function replaces any existing callback
7995 ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
7996 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
7997 ** configured by this function.
7998 **
7999 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
8000 ** from SQL.
8001 **
8002 ** ^Checkpoints initiated by this mechanism are
8003 ** [sqlite3_wal_checkpoint_v2|PASSIVE].
8004 **
8005 ** ^Every new [database connection] defaults to having the auto-checkpoint
8006 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
8007 ** pages. The use of this interface
8008 ** is only necessary if the default setting is found to be suboptimal
8009 ** for a particular application.
8010 */
8011 SQLITE_API int SQLITE_STDCALL sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
8012 
8013 /*
8014 ** CAPI3REF: Checkpoint a database
8015 ** METHOD: sqlite3
8016 **
8017 ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
8018 ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
8019 **
8020 ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
8021 ** [write-ahead log] for database X on [database connection] D to be
8022 ** transferred into the database file and for the write-ahead log to
8023 ** be reset. See the [checkpointing] documentation for addition
8024 ** information.
8025 **
8026 ** This interface used to be the only way to cause a checkpoint to
8027 ** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
8028 ** interface was added. This interface is retained for backwards
8029 ** compatibility and as a convenience for applications that need to manually
8030 ** start a callback but which do not need the full power (and corresponding
8031 ** complication) of [sqlite3_wal_checkpoint_v2()].
8032 */
8033 SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
8034 
8035 /*
8036 ** CAPI3REF: Checkpoint a database
8037 ** METHOD: sqlite3
8038 **
8039 ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
8040 ** operation on database X of [database connection] D in mode M. Status
8041 ** information is written back into integers pointed to by L and C.)^
8042 ** ^(The M parameter must be a valid [checkpoint mode]:)^
8043 **
8044 ** <dl>
8045 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
8046 ** ^Checkpoint as many frames as possible without waiting for any database
8047 ** readers or writers to finish, then sync the database file if all frames
8048 ** in the log were checkpointed. ^The [busy-handler callback]
8049 ** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
8050 ** ^On the other hand, passive mode might leave the checkpoint unfinished
8051 ** if there are concurrent readers or writers.
8052 **
8053 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
8054 ** ^This mode blocks (it invokes the
8055 ** [sqlite3_busy_handler|busy-handler callback]) until there is no
8056 ** database writer and all readers are reading from the most recent database
8057 ** snapshot. ^It then checkpoints all frames in the log file and syncs the
8058 ** database file. ^This mode blocks new database writers while it is pending,
8059 ** but new database readers are allowed to continue unimpeded.
8060 **
8061 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
8062 ** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
8063 ** that after checkpointing the log file it blocks (calls the
8064 ** [busy-handler callback])
8065 ** until all readers are reading from the database file only. ^This ensures
8066 ** that the next writer will restart the log file from the beginning.
8067 ** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
8068 ** database writer attempts while it is pending, but does not impede readers.
8069 **
8070 ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
8071 ** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
8072 ** addition that it also truncates the log file to zero bytes just prior
8073 ** to a successful return.
8074 ** </dl>
8075 **
8076 ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
8077 ** the log file or to -1 if the checkpoint could not run because
8078 ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
8079 ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
8080 ** log file (including any that were already checkpointed before the function
8081 ** was called) or to -1 if the checkpoint could not run due to an error or
8082 ** because the database is not in WAL mode. ^Note that upon successful
8083 ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
8084 ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
8085 **
8086 ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
8087 ** any other process is running a checkpoint operation at the same time, the
8088 ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
8089 ** busy-handler configured, it will not be invoked in this case.
8090 **
8091 ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
8092 ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
8093 ** obtained immediately, and a busy-handler is configured, it is invoked and
8094 ** the writer lock retried until either the busy-handler returns 0 or the lock
8095 ** is successfully obtained. ^The busy-handler is also invoked while waiting for
8096 ** database readers as described above. ^If the busy-handler returns 0 before
8097 ** the writer lock is obtained or while waiting for database readers, the
8098 ** checkpoint operation proceeds from that point in the same way as
8099 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
8100 ** without blocking any further. ^SQLITE_BUSY is returned in this case.
8101 **
8102 ** ^If parameter zDb is NULL or points to a zero length string, then the
8103 ** specified operation is attempted on all WAL databases [attached] to
8104 ** [database connection] db. In this case the
8105 ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
8106 ** an SQLITE_BUSY error is encountered when processing one or more of the
8107 ** attached WAL databases, the operation is still attempted on any remaining
8108 ** attached databases and SQLITE_BUSY is returned at the end. ^If any other
8109 ** error occurs while processing an attached database, processing is abandoned
8110 ** and the error code is returned to the caller immediately. ^If no error
8111 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
8112 ** databases, SQLITE_OK is returned.
8113 **
8114 ** ^If database zDb is the name of an attached database that is not in WAL
8115 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
8116 ** zDb is not NULL (or a zero length string) and is not the name of any
8117 ** attached database, SQLITE_ERROR is returned to the caller.
8118 **
8119 ** ^Unless it returns SQLITE_MISUSE,
8120 ** the sqlite3_wal_checkpoint_v2() interface
8121 ** sets the error information that is queried by
8122 ** [sqlite3_errcode()] and [sqlite3_errmsg()].
8123 **
8124 ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
8125 ** from SQL.
8126 */
8127 SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint_v2(
8128  sqlite3 *db, /* Database handle */
8129  const char *zDb, /* Name of attached database (or NULL) */
8130  int eMode, /* SQLITE_CHECKPOINT_* value */
8131  int *pnLog, /* OUT: Size of WAL log in frames */
8132  int *pnCkpt /* OUT: Total number of frames checkpointed */
8133 );
8134 
8135 /*
8136 ** CAPI3REF: Checkpoint Mode Values
8137 ** KEYWORDS: {checkpoint mode}
8138 **
8139 ** These constants define all valid values for the "checkpoint mode" passed
8140 ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
8141 ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
8142 ** meaning of each of these checkpoint modes.
8143 */
8144 #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */
8145 #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */
8146 #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */
8147 #define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */
8148 
8149 /*
8150 ** CAPI3REF: Virtual Table Interface Configuration
8151 **
8152 ** This function may be called by either the [xConnect] or [xCreate] method
8153 ** of a [virtual table] implementation to configure
8154 ** various facets of the virtual table interface.
8155 **
8156 ** If this interface is invoked outside the context of an xConnect or
8157 ** xCreate virtual table method then the behavior is undefined.
8158 **
8159 ** At present, there is only one option that may be configured using
8160 ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
8161 ** may be added in the future.
8162 */
8163 SQLITE_API int SQLITE_CDECL sqlite3_vtab_config(sqlite3*, int op, ...);
8164 
8165 /*
8166 ** CAPI3REF: Virtual Table Configuration Options
8167 **
8168 ** These macros define the various options to the
8169 ** [sqlite3_vtab_config()] interface that [virtual table] implementations
8170 ** can use to customize and optimize their behavior.
8171 **
8172 ** <dl>
8173 ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
8174 ** <dd>Calls of the form
8175 ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
8176 ** where X is an integer. If X is zero, then the [virtual table] whose
8177 ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
8178 ** support constraints. In this configuration (which is the default) if
8179 ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
8180 ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
8181 ** specified as part of the users SQL statement, regardless of the actual
8182 ** ON CONFLICT mode specified.
8183 **
8184 ** If X is non-zero, then the virtual table implementation guarantees
8185 ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
8186 ** any modifications to internal or persistent data structures have been made.
8187 ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
8188 ** is able to roll back a statement or database transaction, and abandon
8189 ** or continue processing the current SQL statement as appropriate.
8190 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
8191 ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
8192 ** had been ABORT.
8193 **
8194 ** Virtual table implementations that are required to handle OR REPLACE
8195 ** must do so within the [xUpdate] method. If a call to the
8196 ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
8197 ** CONFLICT policy is REPLACE, the virtual table implementation should
8198 ** silently replace the appropriate rows within the xUpdate callback and
8199 ** return SQLITE_OK. Or, if this is not possible, it may return
8200 ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
8201 ** constraint handling.
8202 ** </dl>
8203 */
8204 #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
8205 
8206 /*
8207 ** CAPI3REF: Determine The Virtual Table Conflict Policy
8208 **
8209 ** This function may only be called from within a call to the [xUpdate] method
8210 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
8211 ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
8212 ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
8213 ** of the SQL statement that triggered the call to the [xUpdate] method of the
8214 ** [virtual table].
8215 */
8216 SQLITE_API int SQLITE_STDCALL sqlite3_vtab_on_conflict(sqlite3 *);
8217 
8218 /*
8219 ** CAPI3REF: Conflict resolution modes
8220 ** KEYWORDS: {conflict resolution mode}
8221 **
8222 ** These constants are returned by [sqlite3_vtab_on_conflict()] to
8223 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
8224 ** is for the SQL statement being evaluated.
8225 **
8226 ** Note that the [SQLITE_IGNORE] constant is also used as a potential
8227 ** return value from the [sqlite3_set_authorizer()] callback and that
8228 ** [SQLITE_ABORT] is also a [result code].
8229 */
8230 #define SQLITE_ROLLBACK 1
8231 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
8232 #define SQLITE_FAIL 3
8233 /* #define SQLITE_ABORT 4 // Also an error code */
8234 #define SQLITE_REPLACE 5
8235 
8236 /*
8237 ** CAPI3REF: Prepared Statement Scan Status Opcodes
8238 ** KEYWORDS: {scanstatus options}
8239 **
8240 ** The following constants can be used for the T parameter to the
8241 ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a
8242 ** different metric for sqlite3_stmt_scanstatus() to return.
8243 **
8244 ** When the value returned to V is a string, space to hold that string is
8245 ** managed by the prepared statement S and will be automatically freed when
8246 ** S is finalized.
8247 **
8248 ** <dl>
8249 ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
8250 ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
8251 ** set to the total number of times that the X-th loop has run.</dd>
8252 **
8253 ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
8254 ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
8255 ** to the total number of rows examined by all iterations of the X-th loop.</dd>
8256 **
8257 ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
8258 ** <dd>^The "double" variable pointed to by the T parameter will be set to the
8259 ** query planner's estimate for the average number of rows output from each
8260 ** iteration of the X-th loop. If the query planner's estimates was accurate,
8261 ** then this value will approximate the quotient NVISIT/NLOOP and the
8262 ** product of this value for all prior loops with the same SELECTID will
8263 ** be the NLOOP value for the current loop.
8264 **
8265 ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
8266 ** <dd>^The "const char *" variable pointed to by the T parameter will be set
8267 ** to a zero-terminated UTF-8 string containing the name of the index or table
8268 ** used for the X-th loop.
8269 **
8270 ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
8271 ** <dd>^The "const char *" variable pointed to by the T parameter will be set
8272 ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
8273 ** description for the X-th loop.
8274 **
8275 ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
8276 ** <dd>^The "int" variable pointed to by the T parameter will be set to the
8277 ** "select-id" for the X-th loop. The select-id identifies which query or
8278 ** subquery the loop is part of. The main query has a select-id of zero.
8279 ** The select-id is the same value as is output in the first column
8280 ** of an [EXPLAIN QUERY PLAN] query.
8281 ** </dl>
8282 */
8283 #define SQLITE_SCANSTAT_NLOOP 0
8284 #define SQLITE_SCANSTAT_NVISIT 1
8285 #define SQLITE_SCANSTAT_EST 2
8286 #define SQLITE_SCANSTAT_NAME 3
8287 #define SQLITE_SCANSTAT_EXPLAIN 4
8288 #define SQLITE_SCANSTAT_SELECTID 5
8289 
8290 /*
8291 ** CAPI3REF: Prepared Statement Scan Status
8292 ** METHOD: sqlite3_stmt
8293 **
8294 ** This interface returns information about the predicted and measured
8295 ** performance for pStmt. Advanced applications can use this
8296 ** interface to compare the predicted and the measured performance and
8297 ** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
8298 **
8299 ** Since this interface is expected to be rarely used, it is only
8300 ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
8301 ** compile-time option.
8302 **
8303 ** The "iScanStatusOp" parameter determines which status information to return.
8304 ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
8305 ** of this interface is undefined.
8306 ** ^The requested measurement is written into a variable pointed to by
8307 ** the "pOut" parameter.
8308 ** Parameter "idx" identifies the specific loop to retrieve statistics for.
8309 ** Loops are numbered starting from zero. ^If idx is out of range - less than
8310 ** zero or greater than or equal to the total number of loops used to implement
8311 ** the statement - a non-zero value is returned and the variable that pOut
8312 ** points to is unchanged.
8313 **
8314 ** ^Statistics might not be available for all loops in all statements. ^In cases
8315 ** where there exist loops with no available statistics, this function behaves
8316 ** as if the loop did not exist - it returns non-zero and leave the variable
8317 ** that pOut points to unchanged.
8318 **
8319 ** See also: [sqlite3_stmt_scanstatus_reset()]
8320 */
8321 SQLITE_API int SQLITE_STDCALL sqlite3_stmt_scanstatus(
8322  sqlite3_stmt *pStmt, /* Prepared statement for which info desired */
8323  int idx, /* Index of loop to report on */
8324  int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */
8325  void *pOut /* Result written here */
8326 );
8327 
8328 /*
8329 ** CAPI3REF: Zero Scan-Status Counters
8330 ** METHOD: sqlite3_stmt
8331 **
8332 ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
8333 **
8334 ** This API is only available if the library is built with pre-processor
8335 ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
8336 */
8337 SQLITE_API void SQLITE_STDCALL sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
8338 
8339 /*
8340 ** CAPI3REF: Flush caches to disk mid-transaction
8341 **
8342 ** ^If a write-transaction is open on [database connection] D when the
8343 ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
8344 ** pages in the pager-cache that are not currently in use are written out
8345 ** to disk. A dirty page may be in use if a database cursor created by an
8346 ** active SQL statement is reading from it, or if it is page 1 of a database
8347 ** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)]
8348 ** interface flushes caches for all schemas - "main", "temp", and
8349 ** any [attached] databases.
8350 **
8351 ** ^If this function needs to obtain extra database locks before dirty pages
8352 ** can be flushed to disk, it does so. ^If those locks cannot be obtained
8353 ** immediately and there is a busy-handler callback configured, it is invoked
8354 ** in the usual manner. ^If the required lock still cannot be obtained, then
8355 ** the database is skipped and an attempt made to flush any dirty pages
8356 ** belonging to the next (if any) database. ^If any databases are skipped
8357 ** because locks cannot be obtained, but no other error occurs, this
8358 ** function returns SQLITE_BUSY.
8359 **
8360 ** ^If any other error occurs while flushing dirty pages to disk (for
8361 ** example an IO error or out-of-memory condition), then processing is
8362 ** abandoned and an SQLite [error code] is returned to the caller immediately.
8363 **
8364 ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
8365 **
8366 ** ^This function does not set the database handle error code or message
8367 ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
8368 */
8369 SQLITE_API int SQLITE_STDCALL sqlite3_db_cacheflush(sqlite3*);
8370 
8371 /*
8372 ** CAPI3REF: The pre-update hook.
8373 **
8374 ** ^These interfaces are only available if SQLite is compiled using the
8375 ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
8376 **
8377 ** ^The [sqlite3_preupdate_hook()] interface registers a callback function
8378 ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
8379 ** on a [rowid table].
8380 ** ^At most one preupdate hook may be registered at a time on a single
8381 ** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
8382 ** the previous setting.
8383 ** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
8384 ** with a NULL pointer as the second parameter.
8385 ** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
8386 ** the first parameter to callbacks.
8387 **
8388 ** ^The preupdate hook only fires for changes to [rowid tables]; the preupdate
8389 ** hook is not invoked for changes to [virtual tables] or [WITHOUT ROWID]
8390 ** tables.
8391 **
8392 ** ^The second parameter to the preupdate callback is a pointer to
8393 ** the [database connection] that registered the preupdate hook.
8394 ** ^The third parameter to the preupdate callback is one of the constants
8395 ** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the
8396 ** kind of update operation that is about to occur.
8397 ** ^(The fourth parameter to the preupdate callback is the name of the
8398 ** database within the database connection that is being modified. This
8399 ** will be "main" for the main database or "temp" for TEMP tables or
8400 ** the name given after the AS keyword in the [ATTACH] statement for attached
8401 ** databases.)^
8402 ** ^The fifth parameter to the preupdate callback is the name of the
8403 ** table that is being modified.
8404 ** ^The sixth parameter to the preupdate callback is the initial [rowid] of the
8405 ** row being changes for SQLITE_UPDATE and SQLITE_DELETE changes and is
8406 ** undefined for SQLITE_INSERT changes.
8407 ** ^The seventh parameter to the preupdate callback is the final [rowid] of
8408 ** the row being changed for SQLITE_UPDATE and SQLITE_INSERT changes and is
8409 ** undefined for SQLITE_DELETE changes.
8410 **
8411 ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
8412 ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
8413 ** provide additional information about a preupdate event. These routines
8414 ** may only be called from within a preupdate callback. Invoking any of
8415 ** these routines from outside of a preupdate callback or with a
8416 ** [database connection] pointer that is different from the one supplied
8417 ** to the preupdate callback results in undefined and probably undesirable
8418 ** behavior.
8419 **
8420 ** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
8421 ** in the row that is being inserted, updated, or deleted.
8422 **
8423 ** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
8424 ** a [protected sqlite3_value] that contains the value of the Nth column of
8425 ** the table row before it is updated. The N parameter must be between 0
8426 ** and one less than the number of columns or the behavior will be
8427 ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
8428 ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
8429 ** behavior is undefined. The [sqlite3_value] that P points to
8430 ** will be destroyed when the preupdate callback returns.
8431 **
8432 ** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
8433 ** a [protected sqlite3_value] that contains the value of the Nth column of
8434 ** the table row after it is updated. The N parameter must be between 0
8435 ** and one less than the number of columns or the behavior will be
8436 ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
8437 ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
8438 ** behavior is undefined. The [sqlite3_value] that P points to
8439 ** will be destroyed when the preupdate callback returns.
8440 **
8441 ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
8442 ** callback was invoked as a result of a direct insert, update, or delete
8443 ** operation; or 1 for inserts, updates, or deletes invoked by top-level
8444 ** triggers; or 2 for changes resulting from triggers called by top-level
8445 ** triggers; and so forth.
8446 **
8447 ** See also: [sqlite3_update_hook()]
8448 */
8449 SQLITE_API SQLITE_EXPERIMENTAL void *SQLITE_STDCALL sqlite3_preupdate_hook(
8450  sqlite3 *db,
8451  void(*xPreUpdate)(
8452  void *pCtx, /* Copy of third arg to preupdate_hook() */
8453  sqlite3 *db, /* Database handle */
8454  int op, /* SQLITE_UPDATE, DELETE or INSERT */
8455  char const *zDb, /* Database name */
8456  char const *zName, /* Table name */
8457  sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
8458  sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
8459  ),
8460  void*
8461 );
8462 SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
8463 SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_count(sqlite3 *);
8464 SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_depth(sqlite3 *);
8465 SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
8466 
8467 /*
8468 ** CAPI3REF: Low-level system error code
8469 **
8470 ** ^Attempt to return the underlying operating system error code or error
8471 ** number that caused the most recent I/O error or failure to open a file.
8472 ** The return value is OS-dependent. For example, on unix systems, after
8473 ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
8474 ** called to get back the underlying "errno" that caused the problem, such
8475 ** as ENOSPC, EAUTH, EISDIR, and so forth.
8476 */
8477 SQLITE_API int SQLITE_STDCALL sqlite3_system_errno(sqlite3*);
8478 
8479 /*
8480 ** CAPI3REF: Database Snapshot
8481 ** KEYWORDS: {snapshot}
8482 ** EXPERIMENTAL
8483 **
8484 ** An instance of the snapshot object records the state of a [WAL mode]
8485 ** database for some specific point in history.
8486 **
8487 ** In [WAL mode], multiple [database connections] that are open on the
8488 ** same database file can each be reading a different historical version
8489 ** of the database file. When a [database connection] begins a read
8490 ** transaction, that connection sees an unchanging copy of the database
8491 ** as it existed for the point in time when the transaction first started.
8492 ** Subsequent changes to the database from other connections are not seen
8493 ** by the reader until a new read transaction is started.
8494 **
8495 ** The sqlite3_snapshot object records state information about an historical
8496 ** version of the database file so that it is possible to later open a new read
8497 ** transaction that sees that historical version of the database rather than
8498 ** the most recent version.
8499 **
8500 ** The constructor for this object is [sqlite3_snapshot_get()]. The
8501 ** [sqlite3_snapshot_open()] method causes a fresh read transaction to refer
8502 ** to an historical snapshot (if possible). The destructor for
8503 ** sqlite3_snapshot objects is [sqlite3_snapshot_free()].
8504 */
8505 typedef struct sqlite3_snapshot sqlite3_snapshot;
8506 
8507 /*
8508 ** CAPI3REF: Record A Database Snapshot
8509 ** EXPERIMENTAL
8510 **
8511 ** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
8512 ** new [sqlite3_snapshot] object that records the current state of
8513 ** schema S in database connection D. ^On success, the
8514 ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
8515 ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
8516 ** ^If schema S of [database connection] D is not a [WAL mode] database
8517 ** that is in a read transaction, then [sqlite3_snapshot_get(D,S,P)]
8518 ** leaves the *P value unchanged and returns an appropriate [error code].
8519 **
8520 ** The [sqlite3_snapshot] object returned from a successful call to
8521 ** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
8522 ** to avoid a memory leak.
8523 **
8524 ** The [sqlite3_snapshot_get()] interface is only available when the
8525 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8526 */
8527 SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_snapshot_get(
8528  sqlite3 *db,
8529  const char *zSchema,
8530  sqlite3_snapshot **ppSnapshot
8531 );
8532 
8533 /*
8534 ** CAPI3REF: Start a read transaction on an historical snapshot
8535 ** EXPERIMENTAL
8536 **
8537 ** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a
8538 ** read transaction for schema S of
8539 ** [database connection] D such that the read transaction
8540 ** refers to historical [snapshot] P, rather than the most
8541 ** recent change to the database.
8542 ** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success
8543 ** or an appropriate [error code] if it fails.
8544 **
8545 ** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be
8546 ** the first operation following the [BEGIN] that takes the schema S
8547 ** out of [autocommit mode].
8548 ** ^In other words, schema S must not currently be in
8549 ** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the
8550 ** database connection D must be out of [autocommit mode].
8551 ** ^A [snapshot] will fail to open if it has been overwritten by a
8552 ** [checkpoint].
8553 ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
8554 ** database connection D does not know that the database file for
8555 ** schema S is in [WAL mode]. A database connection might not know
8556 ** that the database file is in [WAL mode] if there has been no prior
8557 ** I/O on that database connection, or if the database entered [WAL mode]
8558 ** after the most recent I/O on the database connection.)^
8559 ** (Hint: Run "[PRAGMA application_id]" against a newly opened
8560 ** database connection in order to make it ready to use snapshots.)
8561 **
8562 ** The [sqlite3_snapshot_open()] interface is only available when the
8563 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8564 */
8565 SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_snapshot_open(
8566  sqlite3 *db,
8567  const char *zSchema,
8568  sqlite3_snapshot *pSnapshot
8569 );
8570 
8571 /*
8572 ** CAPI3REF: Destroy a snapshot
8573 ** EXPERIMENTAL
8574 **
8575 ** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
8576 ** The application must eventually free every [sqlite3_snapshot] object
8577 ** using this routine to avoid a memory leak.
8578 **
8579 ** The [sqlite3_snapshot_free()] interface is only available when the
8580 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8581 */
8582 SQLITE_API SQLITE_EXPERIMENTAL void SQLITE_STDCALL sqlite3_snapshot_free(sqlite3_snapshot*);
8583 
8584 /*
8585 ** CAPI3REF: Compare the ages of two snapshot handles.
8586 ** EXPERIMENTAL
8587 **
8588 ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
8589 ** of two valid snapshot handles.
8590 **
8591 ** If the two snapshot handles are not associated with the same database
8592 ** file, the result of the comparison is undefined.
8593 **
8594 ** Additionally, the result of the comparison is only valid if both of the
8595 ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
8596 ** last time the wal file was deleted. The wal file is deleted when the
8597 ** database is changed back to rollback mode or when the number of database
8598 ** clients drops to zero. If either snapshot handle was obtained before the
8599 ** wal file was last deleted, the value returned by this function
8600 ** is undefined.
8601 **
8602 ** Otherwise, this API returns a negative value if P1 refers to an older
8603 ** snapshot than P2, zero if the two handles refer to the same database
8604 ** snapshot, and a positive value if P1 is a newer snapshot than P2.
8605 */
8606 SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_snapshot_cmp(
8607  sqlite3_snapshot *p1,
8608  sqlite3_snapshot *p2
8609 );
8610 
8611 /*
8612 ** Undo the hack that converts floating point types to integer for
8613 ** builds on processors without floating point support.
8614 */
8615 #ifdef SQLITE_OMIT_FLOATING_POINT
8616 # undef double
8617 #endif
8618 
8619 #if 0
8620 } /* End of the 'extern "C"' block */
8621 #endif
8622 #endif /* SQLITE3_H */
8623 
8624 /******** Begin file sqlite3rtree.h *********/
8625 /*
8626 ** 2010 August 30
8627 **
8628 ** The author disclaims copyright to this source code. In place of
8629 ** a legal notice, here is a blessing:
8630 **
8631 ** May you do good and not evil.
8632 ** May you find forgiveness for yourself and forgive others.
8633 ** May you share freely, never taking more than you give.
8634 **
8635 *************************************************************************
8636 */
8637 
8638 #ifndef _SQLITE3RTREE_H_
8639 #define _SQLITE3RTREE_H_
8640 
8641 
8642 #if 0
8643 extern "C" {
8644 #endif
8645 
8646 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
8647 typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
8648 
8649 /* The double-precision datatype used by RTree depends on the
8650 ** SQLITE_RTREE_INT_ONLY compile-time option.
8651 */
8652 #ifdef SQLITE_RTREE_INT_ONLY
8653  typedef sqlite3_int64 sqlite3_rtree_dbl;
8654 #else
8655  typedef double sqlite3_rtree_dbl;
8656 #endif
8657 
8658 /*
8659 ** Register a geometry callback named zGeom that can be used as part of an
8660 ** R-Tree geometry query as follows:
8661 **
8662 ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
8663 */
8664 SQLITE_API int SQLITE_STDCALL sqlite3_rtree_geometry_callback(
8665  sqlite3 *db,
8666  const char *zGeom,
8667  int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
8668  void *pContext
8669 );
8670 
8671 
8672 /*
8673 ** A pointer to a structure of the following type is passed as the first
8674 ** argument to callbacks registered using rtree_geometry_callback().
8675 */
8676 struct sqlite3_rtree_geometry {
8677  void *pContext; /* Copy of pContext passed to s_r_g_c() */
8678  int nParam; /* Size of array aParam[] */
8679  sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
8680  void *pUser; /* Callback implementation user data */
8681  void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
8682 };
8683 
8684 /*
8685 ** Register a 2nd-generation geometry callback named zScore that can be
8686 ** used as part of an R-Tree geometry query as follows:
8687 **
8688 ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
8689 */
8690 SQLITE_API int SQLITE_STDCALL sqlite3_rtree_query_callback(
8691  sqlite3 *db,
8692  const char *zQueryFunc,
8693  int (*xQueryFunc)(sqlite3_rtree_query_info*),
8694  void *pContext,
8695  void (*xDestructor)(void*)
8696 );
8697 
8698 
8699 /*
8700 ** A pointer to a structure of the following type is passed as the
8701 ** argument to scored geometry callback registered using
8702 ** sqlite3_rtree_query_callback().
8703 **
8704 ** Note that the first 5 fields of this structure are identical to
8705 ** sqlite3_rtree_geometry. This structure is a subclass of
8706 ** sqlite3_rtree_geometry.
8707 */
8708 struct sqlite3_rtree_query_info {
8709  void *pContext; /* pContext from when function registered */
8710  int nParam; /* Number of function parameters */
8711  sqlite3_rtree_dbl *aParam; /* value of function parameters */
8712  void *pUser; /* callback can use this, if desired */
8713  void (*xDelUser)(void*); /* function to free pUser */
8714  sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
8715  unsigned int *anQueue; /* Number of pending entries in the queue */
8716  int nCoord; /* Number of coordinates */
8717  int iLevel; /* Level of current node or entry */
8718  int mxLevel; /* The largest iLevel value in the tree */
8719  sqlite3_int64 iRowid; /* Rowid for current entry */
8720  sqlite3_rtree_dbl rParentScore; /* Score of parent node */
8721  int eParentWithin; /* Visibility of parent node */
8722  int eWithin; /* OUT: Visiblity */
8723  sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
8724  /* The following fields are only available in 3.8.11 and later */
8725  sqlite3_value **apSqlParam; /* Original SQL values of parameters */
8726 };
8727 
8728 /*
8729 ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
8730 */
8731 #define NOT_WITHIN 0 /* Object completely outside of query region */
8732 #define PARTLY_WITHIN 1 /* Object partially overlaps query region */
8733 #define FULLY_WITHIN 2 /* Object fully contained within query region */
8734 
8735 
8736 #if 0
8737 } /* end of the 'extern "C"' block */
8738 #endif
8739 
8740 #endif /* ifndef _SQLITE3RTREE_H_ */
8741 
8742 /******** End of sqlite3rtree.h *********/
8743 /******** Begin file sqlite3session.h *********/
8744 
8745 #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
8746 #define __SQLITESESSION_H_ 1
8747 
8748 /*
8749 ** Make sure we can call this stuff from C++.
8750 */
8751 #if 0
8752 extern "C" {
8753 #endif
8754 
8755 
8756 /*
8757 ** CAPI3REF: Session Object Handle
8758 */
8759 typedef struct sqlite3_session sqlite3_session;
8760 
8761 /*
8762 ** CAPI3REF: Changeset Iterator Handle
8763 */
8764 typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
8765 
8766 /*
8767 ** CAPI3REF: Create A New Session Object
8768 **
8769 ** Create a new session object attached to database handle db. If successful,
8770 ** a pointer to the new object is written to *ppSession and SQLITE_OK is
8771 ** returned. If an error occurs, *ppSession is set to NULL and an SQLite
8772 ** error code (e.g. SQLITE_NOMEM) is returned.
8773 **
8774 ** It is possible to create multiple session objects attached to a single
8775 ** database handle.
8776 **
8777 ** Session objects created using this function should be deleted using the
8778 ** [sqlite3session_delete()] function before the database handle that they
8779 ** are attached to is itself closed. If the database handle is closed before
8780 ** the session object is deleted, then the results of calling any session
8781 ** module function, including [sqlite3session_delete()] on the session object
8782 ** are undefined.
8783 **
8784 ** Because the session module uses the [sqlite3_preupdate_hook()] API, it
8785 ** is not possible for an application to register a pre-update hook on a
8786 ** database handle that has one or more session objects attached. Nor is
8787 ** it possible to create a session object attached to a database handle for
8788 ** which a pre-update hook is already defined. The results of attempting
8789 ** either of these things are undefined.
8790 **
8791 ** The session object will be used to create changesets for tables in
8792 ** database zDb, where zDb is either "main", or "temp", or the name of an
8793 ** attached database. It is not an error if database zDb is not attached
8794 ** to the database when the session object is created.
8795 */
8796 int sqlite3session_create(
8797  sqlite3 *db, /* Database handle */
8798  const char *zDb, /* Name of db (e.g. "main") */
8799  sqlite3_session **ppSession /* OUT: New session object */
8800 );
8801 
8802 /*
8803 ** CAPI3REF: Delete A Session Object
8804 **
8805 ** Delete a session object previously allocated using
8806 ** [sqlite3session_create()]. Once a session object has been deleted, the
8807 ** results of attempting to use pSession with any other session module
8808 ** function are undefined.
8809 **
8810 ** Session objects must be deleted before the database handle to which they
8811 ** are attached is closed. Refer to the documentation for
8812 ** [sqlite3session_create()] for details.
8813 */
8814 void sqlite3session_delete(sqlite3_session *pSession);
8815 
8816 
8817 /*
8818 ** CAPI3REF: Enable Or Disable A Session Object
8819 **
8820 ** Enable or disable the recording of changes by a session object. When
8821 ** enabled, a session object records changes made to the database. When
8822 ** disabled - it does not. A newly created session object is enabled.
8823 ** Refer to the documentation for [sqlite3session_changeset()] for further
8824 ** details regarding how enabling and disabling a session object affects
8825 ** the eventual changesets.
8826 **
8827 ** Passing zero to this function disables the session. Passing a value
8828 ** greater than zero enables it. Passing a value less than zero is a
8829 ** no-op, and may be used to query the current state of the session.
8830 **
8831 ** The return value indicates the final state of the session object: 0 if
8832 ** the session is disabled, or 1 if it is enabled.
8833 */
8834 int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
8835 
8836 /*
8837 ** CAPI3REF: Set Or Clear the Indirect Change Flag
8838 **
8839 ** Each change recorded by a session object is marked as either direct or
8840 ** indirect. A change is marked as indirect if either:
8841 **
8842 ** <ul>
8843 ** <li> The session object "indirect" flag is set when the change is
8844 ** made, or
8845 ** <li> The change is made by an SQL trigger or foreign key action
8846 ** instead of directly as a result of a users SQL statement.
8847 ** </ul>
8848 **
8849 ** If a single row is affected by more than one operation within a session,
8850 ** then the change is considered indirect if all operations meet the criteria
8851 ** for an indirect change above, or direct otherwise.
8852 **
8853 ** This function is used to set, clear or query the session object indirect
8854 ** flag. If the second argument passed to this function is zero, then the
8855 ** indirect flag is cleared. If it is greater than zero, the indirect flag
8856 ** is set. Passing a value less than zero does not modify the current value
8857 ** of the indirect flag, and may be used to query the current state of the
8858 ** indirect flag for the specified session object.
8859 **
8860 ** The return value indicates the final state of the indirect flag: 0 if
8861 ** it is clear, or 1 if it is set.
8862 */
8863 int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
8864 
8865 /*
8866 ** CAPI3REF: Attach A Table To A Session Object
8867 **
8868 ** If argument zTab is not NULL, then it is the name of a table to attach
8869 ** to the session object passed as the first argument. All subsequent changes
8870 ** made to the table while the session object is enabled will be recorded. See
8871 ** documentation for [sqlite3session_changeset()] for further details.
8872 **
8873 ** Or, if argument zTab is NULL, then changes are recorded for all tables
8874 ** in the database. If additional tables are added to the database (by
8875 ** executing "CREATE TABLE" statements) after this call is made, changes for
8876 ** the new tables are also recorded.
8877 **
8878 ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
8879 ** defined as part of their CREATE TABLE statement. It does not matter if the
8880 ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
8881 ** KEY may consist of a single column, or may be a composite key.
8882 **
8883 ** It is not an error if the named table does not exist in the database. Nor
8884 ** is it an error if the named table does not have a PRIMARY KEY. However,
8885 ** no changes will be recorded in either of these scenarios.
8886 **
8887 ** Changes are not recorded for individual rows that have NULL values stored
8888 ** in one or more of their PRIMARY KEY columns.
8889 **
8890 ** SQLITE_OK is returned if the call completes without error. Or, if an error
8891 ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
8892 */
8893 int sqlite3session_attach(
8894  sqlite3_session *pSession, /* Session object */
8895  const char *zTab /* Table name */
8896 );
8897 
8898 /*
8899 ** CAPI3REF: Set a table filter on a Session Object.
8900 **
8901 ** The second argument (xFilter) is the "filter callback". For changes to rows
8902 ** in tables that are not attached to the Session oject, the filter is called
8903 ** to determine whether changes to the table's rows should be tracked or not.
8904 ** If xFilter returns 0, changes is not tracked. Note that once a table is
8905 ** attached, xFilter will not be called again.
8906 */
8907 void sqlite3session_table_filter(
8908  sqlite3_session *pSession, /* Session object */
8909  int(*xFilter)(
8910  void *pCtx, /* Copy of third arg to _filter_table() */
8911  const char *zTab /* Table name */
8912  ),
8913  void *pCtx /* First argument passed to xFilter */
8914 );
8915 
8916 /*
8917 ** CAPI3REF: Generate A Changeset From A Session Object
8918 **
8919 ** Obtain a changeset containing changes to the tables attached to the
8920 ** session object passed as the first argument. If successful,
8921 ** set *ppChangeset to point to a buffer containing the changeset
8922 ** and *pnChangeset to the size of the changeset in bytes before returning
8923 ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
8924 ** zero and return an SQLite error code.
8925 **
8926 ** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
8927 ** each representing a change to a single row of an attached table. An INSERT
8928 ** change contains the values of each field of a new database row. A DELETE
8929 ** contains the original values of each field of a deleted database row. An
8930 ** UPDATE change contains the original values of each field of an updated
8931 ** database row along with the updated values for each updated non-primary-key
8932 ** column. It is not possible for an UPDATE change to represent a change that
8933 ** modifies the values of primary key columns. If such a change is made, it
8934 ** is represented in a changeset as a DELETE followed by an INSERT.
8935 **
8936 ** Changes are not recorded for rows that have NULL values stored in one or
8937 ** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
8938 ** no corresponding change is present in the changesets returned by this
8939 ** function. If an existing row with one or more NULL values stored in
8940 ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
8941 ** only an INSERT is appears in the changeset. Similarly, if an existing row
8942 ** with non-NULL PRIMARY KEY values is updated so that one or more of its
8943 ** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
8944 ** DELETE change only.
8945 **
8946 ** The contents of a changeset may be traversed using an iterator created
8947 ** using the [sqlite3changeset_start()] API. A changeset may be applied to
8948 ** a database with a compatible schema using the [sqlite3changeset_apply()]
8949 ** API.
8950 **
8951 ** Within a changeset generated by this function, all changes related to a
8952 ** single table are grouped together. In other words, when iterating through
8953 ** a changeset or when applying a changeset to a database, all changes related
8954 ** to a single table are processed before moving on to the next table. Tables
8955 ** are sorted in the same order in which they were attached (or auto-attached)
8956 ** to the sqlite3_session object. The order in which the changes related to
8957 ** a single table are stored is undefined.
8958 **
8959 ** Following a successful call to this function, it is the responsibility of
8960 ** the caller to eventually free the buffer that *ppChangeset points to using
8961 ** [sqlite3_free()].
8962 **
8963 ** <h3>Changeset Generation</h3>
8964 **
8965 ** Once a table has been attached to a session object, the session object
8966 ** records the primary key values of all new rows inserted into the table.
8967 ** It also records the original primary key and other column values of any
8968 ** deleted or updated rows. For each unique primary key value, data is only
8969 ** recorded once - the first time a row with said primary key is inserted,
8970 ** updated or deleted in the lifetime of the session.
8971 **
8972 ** There is one exception to the previous paragraph: when a row is inserted,
8973 ** updated or deleted, if one or more of its primary key columns contain a
8974 ** NULL value, no record of the change is made.
8975 **
8976 ** The session object therefore accumulates two types of records - those
8977 ** that consist of primary key values only (created when the user inserts
8978 ** a new record) and those that consist of the primary key values and the
8979 ** original values of other table columns (created when the users deletes
8980 ** or updates a record).
8981 **
8982 ** When this function is called, the requested changeset is created using
8983 ** both the accumulated records and the current contents of the database
8984 ** file. Specifically:
8985 **
8986 ** <ul>
8987 ** <li> For each record generated by an insert, the database is queried
8988 ** for a row with a matching primary key. If one is found, an INSERT
8989 ** change is added to the changeset. If no such row is found, no change
8990 ** is added to the changeset.
8991 **
8992 ** <li> For each record generated by an update or delete, the database is
8993 ** queried for a row with a matching primary key. If such a row is
8994 ** found and one or more of the non-primary key fields have been
8995 ** modified from their original values, an UPDATE change is added to
8996 ** the changeset. Or, if no such row is found in the table, a DELETE
8997 ** change is added to the changeset. If there is a row with a matching
8998 ** primary key in the database, but all fields contain their original
8999 ** values, no change is added to the changeset.
9000 ** </ul>
9001 **
9002 ** This means, amongst other things, that if a row is inserted and then later
9003 ** deleted while a session object is active, neither the insert nor the delete
9004 ** will be present in the changeset. Or if a row is deleted and then later a
9005 ** row with the same primary key values inserted while a session object is
9006 ** active, the resulting changeset will contain an UPDATE change instead of
9007 ** a DELETE and an INSERT.
9008 **
9009 ** When a session object is disabled (see the [sqlite3session_enable()] API),
9010 ** it does not accumulate records when rows are inserted, updated or deleted.
9011 ** This may appear to have some counter-intuitive effects if a single row
9012 ** is written to more than once during a session. For example, if a row
9013 ** is inserted while a session object is enabled, then later deleted while
9014 ** the same session object is disabled, no INSERT record will appear in the
9015 ** changeset, even though the delete took place while the session was disabled.
9016 ** Or, if one field of a row is updated while a session is disabled, and
9017 ** another field of the same row is updated while the session is enabled, the
9018 ** resulting changeset will contain an UPDATE change that updates both fields.
9019 */
9020 int sqlite3session_changeset(
9021  sqlite3_session *pSession, /* Session object */
9022  int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
9023  void **ppChangeset /* OUT: Buffer containing changeset */
9024 );
9025 
9026 /*
9027 ** CAPI3REF: Load The Difference Between Tables Into A Session
9028 **
9029 ** If it is not already attached to the session object passed as the first
9030 ** argument, this function attaches table zTbl in the same manner as the
9031 ** [sqlite3session_attach()] function. If zTbl does not exist, or if it
9032 ** does not have a primary key, this function is a no-op (but does not return
9033 ** an error).
9034 **
9035 ** Argument zFromDb must be the name of a database ("main", "temp" etc.)
9036 ** attached to the same database handle as the session object that contains
9037 ** a table compatible with the table attached to the session by this function.
9038 ** A table is considered compatible if it:
9039 **
9040 ** <ul>
9041 ** <li> Has the same name,
9042 ** <li> Has the same set of columns declared in the same order, and
9043 ** <li> Has the same PRIMARY KEY definition.
9044 ** </ul>
9045 **
9046 ** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
9047 ** are compatible but do not have any PRIMARY KEY columns, it is not an error
9048 ** but no changes are added to the session object. As with other session
9049 ** APIs, tables without PRIMARY KEYs are simply ignored.
9050 **
9051 ** This function adds a set of changes to the session object that could be
9052 ** used to update the table in database zFrom (call this the "from-table")
9053 ** so that its content is the same as the table attached to the session
9054 ** object (call this the "to-table"). Specifically:
9055 **
9056 ** <ul>
9057 ** <li> For each row (primary key) that exists in the to-table but not in
9058 ** the from-table, an INSERT record is added to the session object.
9059 **
9060 ** <li> For each row (primary key) that exists in the to-table but not in
9061 ** the from-table, a DELETE record is added to the session object.
9062 **
9063 ** <li> For each row (primary key) that exists in both tables, but features
9064 ** different in each, an UPDATE record is added to the session.
9065 ** </ul>
9066 **
9067 ** To clarify, if this function is called and then a changeset constructed
9068 ** using [sqlite3session_changeset()], then after applying that changeset to
9069 ** database zFrom the contents of the two compatible tables would be
9070 ** identical.
9071 **
9072 ** It an error if database zFrom does not exist or does not contain the
9073 ** required compatible table.
9074 **
9075 ** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
9076 ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
9077 ** may be set to point to a buffer containing an English language error
9078 ** message. It is the responsibility of the caller to free this buffer using
9079 ** sqlite3_free().
9080 */
9081 int sqlite3session_diff(
9082  sqlite3_session *pSession,
9083  const char *zFromDb,
9084  const char *zTbl,
9085  char **pzErrMsg
9086 );
9087 
9088 
9089 /*
9090 ** CAPI3REF: Generate A Patchset From A Session Object
9091 **
9092 ** The differences between a patchset and a changeset are that:
9093 **
9094 ** <ul>
9095 ** <li> DELETE records consist of the primary key fields only. The
9096 ** original values of other fields are omitted.
9097 ** <li> The original values of any modified fields are omitted from
9098 ** UPDATE records.
9099 ** </ul>
9100 **
9101 ** A patchset blob may be used with up to date versions of all
9102 ** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
9103 ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
9104 ** attempting to use a patchset blob with old versions of the
9105 ** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
9106 **
9107 ** Because the non-primary key "old.*" fields are omitted, no
9108 ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
9109 ** is passed to the sqlite3changeset_apply() API. Other conflict types work
9110 ** in the same way as for changesets.
9111 **
9112 ** Changes within a patchset are ordered in the same way as for changesets
9113 ** generated by the sqlite3session_changeset() function (i.e. all changes for
9114 ** a single table are grouped together, tables appear in the order in which
9115 ** they were attached to the session object).
9116 */
9117 int sqlite3session_patchset(
9118  sqlite3_session *pSession, /* Session object */
9119  int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
9120  void **ppPatchset /* OUT: Buffer containing changeset */
9121 );
9122 
9123 /*
9124 ** CAPI3REF: Test if a changeset has recorded any changes.
9125 **
9126 ** Return non-zero if no changes to attached tables have been recorded by
9127 ** the session object passed as the first argument. Otherwise, if one or
9128 ** more changes have been recorded, return zero.
9129 **
9130 ** Even if this function returns zero, it is possible that calling
9131 ** [sqlite3session_changeset()] on the session handle may still return a
9132 ** changeset that contains no changes. This can happen when a row in
9133 ** an attached table is modified and then later on the original values
9134 ** are restored. However, if this function returns non-zero, then it is
9135 ** guaranteed that a call to sqlite3session_changeset() will return a
9136 ** changeset containing zero changes.
9137 */
9138 int sqlite3session_isempty(sqlite3_session *pSession);
9139 
9140 /*
9141 ** CAPI3REF: Create An Iterator To Traverse A Changeset
9142 **
9143 ** Create an iterator used to iterate through the contents of a changeset.
9144 ** If successful, *pp is set to point to the iterator handle and SQLITE_OK
9145 ** is returned. Otherwise, if an error occurs, *pp is set to zero and an
9146 ** SQLite error code is returned.
9147 **
9148 ** The following functions can be used to advance and query a changeset
9149 ** iterator created by this function:
9150 **
9151 ** <ul>
9152 ** <li> [sqlite3changeset_next()]
9153 ** <li> [sqlite3changeset_op()]
9154 ** <li> [sqlite3changeset_new()]
9155 ** <li> [sqlite3changeset_old()]
9156 ** </ul>
9157 **
9158 ** It is the responsibility of the caller to eventually destroy the iterator
9159 ** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
9160 ** changeset (pChangeset) must remain valid until after the iterator is
9161 ** destroyed.
9162 **
9163 ** Assuming the changeset blob was created by one of the
9164 ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
9165 ** [sqlite3changeset_invert()] functions, all changes within the changeset
9166 ** that apply to a single table are grouped together. This means that when
9167 ** an application iterates through a changeset using an iterator created by
9168 ** this function, all changes that relate to a single table are visted
9169 ** consecutively. There is no chance that the iterator will visit a change
9170 ** the applies to table X, then one for table Y, and then later on visit
9171 ** another change for table X.
9172 */
9173 int sqlite3changeset_start(
9174  sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
9175  int nChangeset, /* Size of changeset blob in bytes */
9176  void *pChangeset /* Pointer to blob containing changeset */
9177 );
9178 
9179 
9180 /*
9181 ** CAPI3REF: Advance A Changeset Iterator
9182 **
9183 ** This function may only be used with iterators created by function
9184 ** [sqlite3changeset_start()]. If it is called on an iterator passed to
9185 ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
9186 ** is returned and the call has no effect.
9187 **
9188 ** Immediately after an iterator is created by sqlite3changeset_start(), it
9189 ** does not point to any change in the changeset. Assuming the changeset
9190 ** is not empty, the first call to this function advances the iterator to
9191 ** point to the first change in the changeset. Each subsequent call advances
9192 ** the iterator to point to the next change in the changeset (if any). If
9193 ** no error occurs and the iterator points to a valid change after a call
9194 ** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
9195 ** Otherwise, if all changes in the changeset have already been visited,
9196 ** SQLITE_DONE is returned.
9197 **
9198 ** If an error occurs, an SQLite error code is returned. Possible error
9199 ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
9200 ** SQLITE_NOMEM.
9201 */
9202 int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
9203 
9204 /*
9205 ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
9206 **
9207 ** The pIter argument passed to this function may either be an iterator
9208 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
9209 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
9210 ** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
9211 ** is not the case, this function returns [SQLITE_MISUSE].
9212 **
9213 ** If argument pzTab is not NULL, then *pzTab is set to point to a
9214 ** nul-terminated utf-8 encoded string containing the name of the table
9215 ** affected by the current change. The buffer remains valid until either
9216 ** sqlite3changeset_next() is called on the iterator or until the
9217 ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
9218 ** set to the number of columns in the table affected by the change. If
9219 ** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change
9220 ** is an indirect change, or false (0) otherwise. See the documentation for
9221 ** [sqlite3session_indirect()] for a description of direct and indirect
9222 ** changes. Finally, if pOp is not NULL, then *pOp is set to one of
9223 ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
9224 ** type of change that the iterator currently points to.
9225 **
9226 ** If no error occurs, SQLITE_OK is returned. If an error does occur, an
9227 ** SQLite error code is returned. The values of the output variables may not
9228 ** be trusted in this case.
9229 */
9230 int sqlite3changeset_op(
9231  sqlite3_changeset_iter *pIter, /* Iterator object */
9232  const char **pzTab, /* OUT: Pointer to table name */
9233  int *pnCol, /* OUT: Number of columns in table */
9234  int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
9235  int *pbIndirect /* OUT: True for an 'indirect' change */
9236 );
9237 
9238 /*
9239 ** CAPI3REF: Obtain The Primary Key Definition Of A Table
9240 **
9241 ** For each modified table, a changeset includes the following:
9242 **
9243 ** <ul>
9244 ** <li> The number of columns in the table, and
9245 ** <li> Which of those columns make up the tables PRIMARY KEY.
9246 ** </ul>
9247 **
9248 ** This function is used to find which columns comprise the PRIMARY KEY of
9249 ** the table modified by the change that iterator pIter currently points to.
9250 ** If successful, *pabPK is set to point to an array of nCol entries, where
9251 ** nCol is the number of columns in the table. Elements of *pabPK are set to
9252 ** 0x01 if the corresponding column is part of the tables primary key, or
9253 ** 0x00 if it is not.
9254 **
9255 ** If argumet pnCol is not NULL, then *pnCol is set to the number of columns
9256 ** in the table.
9257 **
9258 ** If this function is called when the iterator does not point to a valid
9259 ** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
9260 ** SQLITE_OK is returned and the output variables populated as described
9261 ** above.
9262 */
9263 int sqlite3changeset_pk(
9264  sqlite3_changeset_iter *pIter, /* Iterator object */
9265  unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
9266  int *pnCol /* OUT: Number of entries in output array */
9267 );
9268 
9269 /*
9270 ** CAPI3REF: Obtain old.* Values From A Changeset Iterator
9271 **
9272 ** The pIter argument passed to this function may either be an iterator
9273 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
9274 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
9275 ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
9276 ** Furthermore, it may only be called if the type of change that the iterator
9277 ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
9278 ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
9279 **
9280 ** Argument iVal must be greater than or equal to 0, and less than the number
9281 ** of columns in the table affected by the current change. Otherwise,
9282 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
9283 **
9284 ** If successful, this function sets *ppValue to point to a protected
9285 ** sqlite3_value object containing the iVal'th value from the vector of
9286 ** original row values stored as part of the UPDATE or DELETE change and
9287 ** returns SQLITE_OK. The name of the function comes from the fact that this
9288 ** is similar to the "old.*" columns available to update or delete triggers.
9289 **
9290 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
9291 ** is returned and *ppValue is set to NULL.
9292 */
9293 int sqlite3changeset_old(
9294  sqlite3_changeset_iter *pIter, /* Changeset iterator */
9295  int iVal, /* Column number */
9296  sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
9297 );
9298 
9299 /*
9300 ** CAPI3REF: Obtain new.* Values From A Changeset Iterator
9301 **
9302 ** The pIter argument passed to this function may either be an iterator
9303 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
9304 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
9305 ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
9306 ** Furthermore, it may only be called if the type of change that the iterator
9307 ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
9308 ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
9309 **
9310 ** Argument iVal must be greater than or equal to 0, and less than the number
9311 ** of columns in the table affected by the current change. Otherwise,
9312 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
9313 **
9314 ** If successful, this function sets *ppValue to point to a protected
9315 ** sqlite3_value object containing the iVal'th value from the vector of
9316 ** new row values stored as part of the UPDATE or INSERT change and
9317 ** returns SQLITE_OK. If the change is an UPDATE and does not include
9318 ** a new value for the requested column, *ppValue is set to NULL and
9319 ** SQLITE_OK returned. The name of the function comes from the fact that
9320 ** this is similar to the "new.*" columns available to update or delete
9321 ** triggers.
9322 **
9323 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
9324 ** is returned and *ppValue is set to NULL.
9325 */
9326 int sqlite3changeset_new(
9327  sqlite3_changeset_iter *pIter, /* Changeset iterator */
9328  int iVal, /* Column number */
9329  sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
9330 );
9331 
9332 /*
9333 ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
9334 **
9335 ** This function should only be used with iterator objects passed to a
9336 ** conflict-handler callback by [sqlite3changeset_apply()] with either
9337 ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
9338 ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
9339 ** is set to NULL.
9340 **
9341 ** Argument iVal must be greater than or equal to 0, and less than the number
9342 ** of columns in the table affected by the current change. Otherwise,
9343 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
9344 **
9345 ** If successful, this function sets *ppValue to point to a protected
9346 ** sqlite3_value object containing the iVal'th value from the
9347 ** "conflicting row" associated with the current conflict-handler callback
9348 ** and returns SQLITE_OK.
9349 **
9350 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
9351 ** is returned and *ppValue is set to NULL.
9352 */
9353 int sqlite3changeset_conflict(
9354  sqlite3_changeset_iter *pIter, /* Changeset iterator */
9355  int iVal, /* Column number */
9356  sqlite3_value **ppValue /* OUT: Value from conflicting row */
9357 );
9358 
9359 /*
9360 ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
9361 **
9362 ** This function may only be called with an iterator passed to an
9363 ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
9364 ** it sets the output variable to the total number of known foreign key
9365 ** violations in the destination database and returns SQLITE_OK.
9366 **
9367 ** In all other cases this function returns SQLITE_MISUSE.
9368 */
9369 int sqlite3changeset_fk_conflicts(
9370  sqlite3_changeset_iter *pIter, /* Changeset iterator */
9371  int *pnOut /* OUT: Number of FK violations */
9372 );
9373 
9374 
9375 /*
9376 ** CAPI3REF: Finalize A Changeset Iterator
9377 **
9378 ** This function is used to finalize an iterator allocated with
9379 ** [sqlite3changeset_start()].
9380 **
9381 ** This function should only be called on iterators created using the
9382 ** [sqlite3changeset_start()] function. If an application calls this
9383 ** function with an iterator passed to a conflict-handler by
9384 ** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
9385 ** call has no effect.
9386 **
9387 ** If an error was encountered within a call to an sqlite3changeset_xxx()
9388 ** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
9389 ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
9390 ** to that error is returned by this function. Otherwise, SQLITE_OK is
9391 ** returned. This is to allow the following pattern (pseudo-code):
9392 **
9393 ** sqlite3changeset_start();
9394 ** while( SQLITE_ROW==sqlite3changeset_next() ){
9395 ** // Do something with change.
9396 ** }
9397 ** rc = sqlite3changeset_finalize();
9398 ** if( rc!=SQLITE_OK ){
9399 ** // An error has occurred
9400 ** }
9401 */
9402 int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
9403 
9404 /*
9405 ** CAPI3REF: Invert A Changeset
9406 **
9407 ** This function is used to "invert" a changeset object. Applying an inverted
9408 ** changeset to a database reverses the effects of applying the uninverted
9409 ** changeset. Specifically:
9410 **
9411 ** <ul>
9412 ** <li> Each DELETE change is changed to an INSERT, and
9413 ** <li> Each INSERT change is changed to a DELETE, and
9414 ** <li> For each UPDATE change, the old.* and new.* values are exchanged.
9415 ** </ul>
9416 **
9417 ** This function does not change the order in which changes appear within
9418 ** the changeset. It merely reverses the sense of each individual change.
9419 **
9420 ** If successful, a pointer to a buffer containing the inverted changeset
9421 ** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
9422 ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
9423 ** zeroed and an SQLite error code returned.
9424 **
9425 ** It is the responsibility of the caller to eventually call sqlite3_free()
9426 ** on the *ppOut pointer to free the buffer allocation following a successful
9427 ** call to this function.
9428 **
9429 ** WARNING/TODO: This function currently assumes that the input is a valid
9430 ** changeset. If it is not, the results are undefined.
9431 */
9432 int sqlite3changeset_invert(
9433  int nIn, const void *pIn, /* Input changeset */
9434  int *pnOut, void **ppOut /* OUT: Inverse of input */
9435 );
9436 
9437 /*
9438 ** CAPI3REF: Concatenate Two Changeset Objects
9439 **
9440 ** This function is used to concatenate two changesets, A and B, into a
9441 ** single changeset. The result is a changeset equivalent to applying
9442 ** changeset A followed by changeset B.
9443 **
9444 ** This function combines the two input changesets using an
9445 ** sqlite3_changegroup object. Calling it produces similar results as the
9446 ** following code fragment:
9447 **
9448 ** sqlite3_changegroup *pGrp;
9449 ** rc = sqlite3_changegroup_new(&pGrp);
9450 ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
9451 ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
9452 ** if( rc==SQLITE_OK ){
9453 ** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
9454 ** }else{
9455 ** *ppOut = 0;
9456 ** *pnOut = 0;
9457 ** }
9458 **
9459 ** Refer to the sqlite3_changegroup documentation below for details.
9460 */
9461 int sqlite3changeset_concat(
9462  int nA, /* Number of bytes in buffer pA */
9463  void *pA, /* Pointer to buffer containing changeset A */
9464  int nB, /* Number of bytes in buffer pB */
9465  void *pB, /* Pointer to buffer containing changeset B */
9466  int *pnOut, /* OUT: Number of bytes in output changeset */
9467  void **ppOut /* OUT: Buffer containing output changeset */
9468 );
9469 
9470 
9471 /*
9472 ** Changegroup handle.
9473 */
9474 typedef struct sqlite3_changegroup sqlite3_changegroup;
9475 
9476 /*
9477 ** CAPI3REF: Combine two or more changesets into a single changeset.
9478 **
9479 ** An sqlite3_changegroup object is used to combine two or more changesets
9480 ** (or patchsets) into a single changeset (or patchset). A single changegroup
9481 ** object may combine changesets or patchsets, but not both. The output is
9482 ** always in the same format as the input.
9483 **
9484 ** If successful, this function returns SQLITE_OK and populates (*pp) with
9485 ** a pointer to a new sqlite3_changegroup object before returning. The caller
9486 ** should eventually free the returned object using a call to
9487 ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
9488 ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
9489 **
9490 ** The usual usage pattern for an sqlite3_changegroup object is as follows:
9491 **
9492 ** <ul>
9493 ** <li> It is created using a call to sqlite3changegroup_new().
9494 **
9495 ** <li> Zero or more changesets (or patchsets) are added to the object
9496 ** by calling sqlite3changegroup_add().
9497 **
9498 ** <li> The result of combining all input changesets together is obtained
9499 ** by the application via a call to sqlite3changegroup_output().
9500 **
9501 ** <li> The object is deleted using a call to sqlite3changegroup_delete().
9502 ** </ul>
9503 **
9504 ** Any number of calls to add() and output() may be made between the calls to
9505 ** new() and delete(), and in any order.
9506 **
9507 ** As well as the regular sqlite3changegroup_add() and
9508 ** sqlite3changegroup_output() functions, also available are the streaming
9509 ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
9510 */
9511 int sqlite3changegroup_new(sqlite3_changegroup **pp);
9512 
9513 /*
9514 ** Add all changes within the changeset (or patchset) in buffer pData (size
9515 ** nData bytes) to the changegroup.
9516 **
9517 ** If the buffer contains a patchset, then all prior calls to this function
9518 ** on the same changegroup object must also have specified patchsets. Or, if
9519 ** the buffer contains a changeset, so must have the earlier calls to this
9520 ** function. Otherwise, SQLITE_ERROR is returned and no changes are added
9521 ** to the changegroup.
9522 **
9523 ** Rows within the changeset and changegroup are identified by the values in
9524 ** their PRIMARY KEY columns. A change in the changeset is considered to
9525 ** apply to the same row as a change already present in the changegroup if
9526 ** the two rows have the same primary key.
9527 **
9528 ** Changes to rows that that do not already appear in the changegroup are
9529 ** simply copied into it. Or, if both the new changeset and the changegroup
9530 ** contain changes that apply to a single row, the final contents of the
9531 ** changegroup depends on the type of each change, as follows:
9532 **
9533 ** <table border=1 style="margin-left:8ex;margin-right:8ex">
9534 ** <tr><th style="white-space:pre">Existing Change </th>
9535 ** <th style="white-space:pre">New Change </th>
9536 ** <th>Output Change
9537 ** <tr><td>INSERT <td>INSERT <td>
9538 ** The new change is ignored. This case does not occur if the new
9539 ** changeset was recorded immediately after the changesets already
9540 ** added to the changegroup.
9541 ** <tr><td>INSERT <td>UPDATE <td>
9542 ** The INSERT change remains in the changegroup. The values in the
9543 ** INSERT change are modified as if the row was inserted by the
9544 ** existing change and then updated according to the new change.
9545 ** <tr><td>INSERT <td>DELETE <td>
9546 ** The existing INSERT is removed from the changegroup. The DELETE is
9547 ** not added.
9548 ** <tr><td>UPDATE <td>INSERT <td>
9549 ** The new change is ignored. This case does not occur if the new
9550 ** changeset was recorded immediately after the changesets already
9551 ** added to the changegroup.
9552 ** <tr><td>UPDATE <td>UPDATE <td>
9553 ** The existing UPDATE remains within the changegroup. It is amended
9554 ** so that the accompanying values are as if the row was updated once
9555 ** by the existing change and then again by the new change.
9556 ** <tr><td>UPDATE <td>DELETE <td>
9557 ** The existing UPDATE is replaced by the new DELETE within the
9558 ** changegroup.
9559 ** <tr><td>DELETE <td>INSERT <td>
9560 ** If one or more of the column values in the row inserted by the
9561 ** new change differ from those in the row deleted by the existing
9562 ** change, the existing DELETE is replaced by an UPDATE within the
9563 ** changegroup. Otherwise, if the inserted row is exactly the same
9564 ** as the deleted row, the existing DELETE is simply discarded.
9565 ** <tr><td>DELETE <td>UPDATE <td>
9566 ** The new change is ignored. This case does not occur if the new
9567 ** changeset was recorded immediately after the changesets already
9568 ** added to the changegroup.
9569 ** <tr><td>DELETE <td>DELETE <td>
9570 ** The new change is ignored. This case does not occur if the new
9571 ** changeset was recorded immediately after the changesets already
9572 ** added to the changegroup.
9573 ** </table>
9574 **
9575 ** If the new changeset contains changes to a table that is already present
9576 ** in the changegroup, then the number of columns and the position of the
9577 ** primary key columns for the table must be consistent. If this is not the
9578 ** case, this function fails with SQLITE_SCHEMA. If the input changeset
9579 ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
9580 ** returned. Or, if an out-of-memory condition occurs during processing, this
9581 ** function returns SQLITE_NOMEM. In all cases, if an error occurs the
9582 ** final contents of the changegroup is undefined.
9583 **
9584 ** If no error occurs, SQLITE_OK is returned.
9585 */
9586 int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
9587 
9588 /*
9589 ** Obtain a buffer containing a changeset (or patchset) representing the
9590 ** current contents of the changegroup. If the inputs to the changegroup
9591 ** were themselves changesets, the output is a changeset. Or, if the
9592 ** inputs were patchsets, the output is also a patchset.
9593 **
9594 ** As with the output of the sqlite3session_changeset() and
9595 ** sqlite3session_patchset() functions, all changes related to a single
9596 ** table are grouped together in the output of this function. Tables appear
9597 ** in the same order as for the very first changeset added to the changegroup.
9598 ** If the second or subsequent changesets added to the changegroup contain
9599 ** changes for tables that do not appear in the first changeset, they are
9600 ** appended onto the end of the output changeset, again in the order in
9601 ** which they are first encountered.
9602 **
9603 ** If an error occurs, an SQLite error code is returned and the output
9604 ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
9605 ** is returned and the output variables are set to the size of and a
9606 ** pointer to the output buffer, respectively. In this case it is the
9607 ** responsibility of the caller to eventually free the buffer using a
9608 ** call to sqlite3_free().
9609 */
9610 int sqlite3changegroup_output(
9611  sqlite3_changegroup*,
9612  int *pnData, /* OUT: Size of output buffer in bytes */
9613  void **ppData /* OUT: Pointer to output buffer */
9614 );
9615 
9616 /*
9617 ** Delete a changegroup object.
9618 */
9619 void sqlite3changegroup_delete(sqlite3_changegroup*);
9620 
9621 /*
9622 ** CAPI3REF: Apply A Changeset To A Database
9623 **
9624 ** Apply a changeset to a database. This function attempts to update the
9625 ** "main" database attached to handle db with the changes found in the
9626 ** changeset passed via the second and third arguments.
9627 **
9628 ** The fourth argument (xFilter) passed to this function is the "filter
9629 ** callback". If it is not NULL, then for each table affected by at least one
9630 ** change in the changeset, the filter callback is invoked with
9631 ** the table name as the second argument, and a copy of the context pointer
9632 ** passed as the sixth argument to this function as the first. If the "filter
9633 ** callback" returns zero, then no attempt is made to apply any changes to
9634 ** the table. Otherwise, if the return value is non-zero or the xFilter
9635 ** argument to this function is NULL, all changes related to the table are
9636 ** attempted.
9637 **
9638 ** For each table that is not excluded by the filter callback, this function
9639 ** tests that the target database contains a compatible table. A table is
9640 ** considered compatible if all of the following are true:
9641 **
9642 ** <ul>
9643 ** <li> The table has the same name as the name recorded in the
9644 ** changeset, and
9645 ** <li> The table has the same number of columns as recorded in the
9646 ** changeset, and
9647 ** <li> The table has primary key columns in the same position as
9648 ** recorded in the changeset.
9649 ** </ul>
9650 **
9651 ** If there is no compatible table, it is not an error, but none of the
9652 ** changes associated with the table are applied. A warning message is issued
9653 ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
9654 ** one such warning is issued for each table in the changeset.
9655 **
9656 ** For each change for which there is a compatible table, an attempt is made
9657 ** to modify the table contents according to the UPDATE, INSERT or DELETE
9658 ** change. If a change cannot be applied cleanly, the conflict handler
9659 ** function passed as the fifth argument to sqlite3changeset_apply() may be
9660 ** invoked. A description of exactly when the conflict handler is invoked for
9661 ** each type of change is below.
9662 **
9663 ** Unlike the xFilter argument, xConflict may not be passed NULL. The results
9664 ** of passing anything other than a valid function pointer as the xConflict
9665 ** argument are undefined.
9666 **
9667 ** Each time the conflict handler function is invoked, it must return one
9668 ** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
9669 ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
9670 ** if the second argument passed to the conflict handler is either
9671 ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
9672 ** returns an illegal value, any changes already made are rolled back and
9673 ** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
9674 ** actions are taken by sqlite3changeset_apply() depending on the value
9675 ** returned by each invocation of the conflict-handler function. Refer to
9676 ** the documentation for the three
9677 ** [SQLITE_CHANGESET_OMIT|available return values] for details.
9678 **
9679 ** <dl>
9680 ** <dt>DELETE Changes<dd>
9681 ** For each DELETE change, this function checks if the target database
9682 ** contains a row with the same primary key value (or values) as the
9683 ** original row values stored in the changeset. If it does, and the values
9684 ** stored in all non-primary key columns also match the values stored in
9685 ** the changeset the row is deleted from the target database.
9686 **
9687 ** If a row with matching primary key values is found, but one or more of
9688 ** the non-primary key fields contains a value different from the original
9689 ** row value stored in the changeset, the conflict-handler function is
9690 ** invoked with [SQLITE_CHANGESET_DATA] as the second argument.
9691 **
9692 ** If no row with matching primary key values is found in the database,
9693 ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
9694 ** passed as the second argument.
9695 **
9696 ** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
9697 ** (which can only happen if a foreign key constraint is violated), the
9698 ** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
9699 ** passed as the second argument. This includes the case where the DELETE
9700 ** operation is attempted because an earlier call to the conflict handler
9701 ** function returned [SQLITE_CHANGESET_REPLACE].
9702 **
9703 ** <dt>INSERT Changes<dd>
9704 ** For each INSERT change, an attempt is made to insert the new row into
9705 ** the database.
9706 **
9707 ** If the attempt to insert the row fails because the database already
9708 ** contains a row with the same primary key values, the conflict handler
9709 ** function is invoked with the second argument set to
9710 ** [SQLITE_CHANGESET_CONFLICT].
9711 **
9712 ** If the attempt to insert the row fails because of some other constraint
9713 ** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
9714 ** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
9715 ** This includes the case where the INSERT operation is re-attempted because
9716 ** an earlier call to the conflict handler function returned
9717 ** [SQLITE_CHANGESET_REPLACE].
9718 **
9719 ** <dt>UPDATE Changes<dd>
9720 ** For each UPDATE change, this function checks if the target database
9721 ** contains a row with the same primary key value (or values) as the
9722 ** original row values stored in the changeset. If it does, and the values
9723 ** stored in all non-primary key columns also match the values stored in
9724 ** the changeset the row is updated within the target database.
9725 **
9726 ** If a row with matching primary key values is found, but one or more of
9727 ** the non-primary key fields contains a value different from an original
9728 ** row value stored in the changeset, the conflict-handler function is
9729 ** invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
9730 ** UPDATE changes only contain values for non-primary key fields that are
9731 ** to be modified, only those fields need to match the original values to
9732 ** avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
9733 **
9734 ** If no row with matching primary key values is found in the database,
9735 ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
9736 ** passed as the second argument.
9737 **
9738 ** If the UPDATE operation is attempted, but SQLite returns
9739 ** SQLITE_CONSTRAINT, the conflict-handler function is invoked with
9740 ** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
9741 ** This includes the case where the UPDATE operation is attempted after
9742 ** an earlier call to the conflict handler function returned
9743 ** [SQLITE_CHANGESET_REPLACE].
9744 ** </dl>
9745 **
9746 ** It is safe to execute SQL statements, including those that write to the
9747 ** table that the callback related to, from within the xConflict callback.
9748 ** This can be used to further customize the applications conflict
9749 ** resolution strategy.
9750 **
9751 ** All changes made by this function are enclosed in a savepoint transaction.
9752 ** If any other error (aside from a constraint failure when attempting to
9753 ** write to the target database) occurs, then the savepoint transaction is
9754 ** rolled back, restoring the target database to its original state, and an
9755 ** SQLite error code returned.
9756 */
9757 int sqlite3changeset_apply(
9758  sqlite3 *db, /* Apply change to "main" db of this handle */
9759  int nChangeset, /* Size of changeset in bytes */
9760  void *pChangeset, /* Changeset blob */
9761  int(*xFilter)(
9762  void *pCtx, /* Copy of sixth arg to _apply() */
9763  const char *zTab /* Table name */
9764  ),
9765  int(*xConflict)(
9766  void *pCtx, /* Copy of sixth arg to _apply() */
9767  int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
9768  sqlite3_changeset_iter *p /* Handle describing change and conflict */
9769  ),
9770  void *pCtx /* First argument passed to xConflict */
9771 );
9772 
9773 /*
9774 ** CAPI3REF: Constants Passed To The Conflict Handler
9775 **
9776 ** Values that may be passed as the second argument to a conflict-handler.
9777 **
9778 ** <dl>
9779 ** <dt>SQLITE_CHANGESET_DATA<dd>
9780 ** The conflict handler is invoked with CHANGESET_DATA as the second argument
9781 ** when processing a DELETE or UPDATE change if a row with the required
9782 ** PRIMARY KEY fields is present in the database, but one or more other
9783 ** (non primary-key) fields modified by the update do not contain the
9784 ** expected "before" values.
9785 **
9786 ** The conflicting row, in this case, is the database row with the matching
9787 ** primary key.
9788 **
9789 ** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
9790 ** The conflict handler is invoked with CHANGESET_NOTFOUND as the second
9791 ** argument when processing a DELETE or UPDATE change if a row with the
9792 ** required PRIMARY KEY fields is not present in the database.
9793 **
9794 ** There is no conflicting row in this case. The results of invoking the
9795 ** sqlite3changeset_conflict() API are undefined.
9796 **
9797 ** <dt>SQLITE_CHANGESET_CONFLICT<dd>
9798 ** CHANGESET_CONFLICT is passed as the second argument to the conflict
9799 ** handler while processing an INSERT change if the operation would result
9800 ** in duplicate primary key values.
9801 **
9802 ** The conflicting row in this case is the database row with the matching
9803 ** primary key.
9804 **
9805 ** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
9806 ** If foreign key handling is enabled, and applying a changeset leaves the
9807 ** database in a state containing foreign key violations, the conflict
9808 ** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
9809 ** exactly once before the changeset is committed. If the conflict handler
9810 ** returns CHANGESET_OMIT, the changes, including those that caused the
9811 ** foreign key constraint violation, are committed. Or, if it returns
9812 ** CHANGESET_ABORT, the changeset is rolled back.
9813 **
9814 ** No current or conflicting row information is provided. The only function
9815 ** it is possible to call on the supplied sqlite3_changeset_iter handle
9816 ** is sqlite3changeset_fk_conflicts().
9817 **
9818 ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
9819 ** If any other constraint violation occurs while applying a change (i.e.
9820 ** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
9821 ** invoked with CHANGESET_CONSTRAINT as the second argument.
9822 **
9823 ** There is no conflicting row in this case. The results of invoking the
9824 ** sqlite3changeset_conflict() API are undefined.
9825 **
9826 ** </dl>
9827 */
9828 #define SQLITE_CHANGESET_DATA 1
9829 #define SQLITE_CHANGESET_NOTFOUND 2
9830 #define SQLITE_CHANGESET_CONFLICT 3
9831 #define SQLITE_CHANGESET_CONSTRAINT 4
9832 #define SQLITE_CHANGESET_FOREIGN_KEY 5
9833 
9834 /*
9835 ** CAPI3REF: Constants Returned By The Conflict Handler
9836 **
9837 ** A conflict handler callback must return one of the following three values.
9838 **
9839 ** <dl>
9840 ** <dt>SQLITE_CHANGESET_OMIT<dd>
9841 ** If a conflict handler returns this value no special action is taken. The
9842 ** change that caused the conflict is not applied. The session module
9843 ** continues to the next change in the changeset.
9844 **
9845 ** <dt>SQLITE_CHANGESET_REPLACE<dd>
9846 ** This value may only be returned if the second argument to the conflict
9847 ** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
9848 ** is not the case, any changes applied so far are rolled back and the
9849 ** call to sqlite3changeset_apply() returns SQLITE_MISUSE.
9850 **
9851 ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
9852 ** handler, then the conflicting row is either updated or deleted, depending
9853 ** on the type of change.
9854 **
9855 ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
9856 ** handler, then the conflicting row is removed from the database and a
9857 ** second attempt to apply the change is made. If this second attempt fails,
9858 ** the original row is restored to the database before continuing.
9859 **
9860 ** <dt>SQLITE_CHANGESET_ABORT<dd>
9861 ** If this value is returned, any changes applied so far are rolled back
9862 ** and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
9863 ** </dl>
9864 */
9865 #define SQLITE_CHANGESET_OMIT 0
9866 #define SQLITE_CHANGESET_REPLACE 1
9867 #define SQLITE_CHANGESET_ABORT 2
9868 
9869 /*
9870 ** CAPI3REF: Streaming Versions of API functions.
9871 **
9872 ** The six streaming API xxx_strm() functions serve similar purposes to the
9873 ** corresponding non-streaming API functions:
9874 **
9875 ** <table border=1 style="margin-left:8ex;margin-right:8ex">
9876 ** <tr><th>Streaming function<th>Non-streaming equivalent</th>
9877 ** <tr><td>sqlite3changeset_apply_str<td>[sqlite3changeset_apply]
9878 ** <tr><td>sqlite3changeset_concat_str<td>[sqlite3changeset_concat]
9879 ** <tr><td>sqlite3changeset_invert_str<td>[sqlite3changeset_invert]
9880 ** <tr><td>sqlite3changeset_start_str<td>[sqlite3changeset_start]
9881 ** <tr><td>sqlite3session_changeset_str<td>[sqlite3session_changeset]
9882 ** <tr><td>sqlite3session_patchset_str<td>[sqlite3session_patchset]
9883 ** </table>
9884 **
9885 ** Non-streaming functions that accept changesets (or patchsets) as input
9886 ** require that the entire changeset be stored in a single buffer in memory.
9887 ** Similarly, those that return a changeset or patchset do so by returning
9888 ** a pointer to a single large buffer allocated using sqlite3_malloc().
9889 ** Normally this is convenient. However, if an application running in a
9890 ** low-memory environment is required to handle very large changesets, the
9891 ** large contiguous memory allocations required can become onerous.
9892 **
9893 ** In order to avoid this problem, instead of a single large buffer, input
9894 ** is passed to a streaming API functions by way of a callback function that
9895 ** the sessions module invokes to incrementally request input data as it is
9896 ** required. In all cases, a pair of API function parameters such as
9897 **
9898 ** <pre>
9899 ** &nbsp; int nChangeset,
9900 ** &nbsp; void *pChangeset,
9901 ** </pre>
9902 **
9903 ** Is replaced by:
9904 **
9905 ** <pre>
9906 ** &nbsp; int (*xInput)(void *pIn, void *pData, int *pnData),
9907 ** &nbsp; void *pIn,
9908 ** </pre>
9909 **
9910 ** Each time the xInput callback is invoked by the sessions module, the first
9911 ** argument passed is a copy of the supplied pIn context pointer. The second
9912 ** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
9913 ** error occurs the xInput method should copy up to (*pnData) bytes of data
9914 ** into the buffer and set (*pnData) to the actual number of bytes copied
9915 ** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
9916 ** should be set to zero to indicate this. Or, if an error occurs, an SQLite
9917 ** error code should be returned. In all cases, if an xInput callback returns
9918 ** an error, all processing is abandoned and the streaming API function
9919 ** returns a copy of the error code to the caller.
9920 **
9921 ** In the case of sqlite3changeset_start_strm(), the xInput callback may be
9922 ** invoked by the sessions module at any point during the lifetime of the
9923 ** iterator. If such an xInput callback returns an error, the iterator enters
9924 ** an error state, whereby all subsequent calls to iterator functions
9925 ** immediately fail with the same error code as returned by xInput.
9926 **
9927 ** Similarly, streaming API functions that return changesets (or patchsets)
9928 ** return them in chunks by way of a callback function instead of via a
9929 ** pointer to a single large buffer. In this case, a pair of parameters such
9930 ** as:
9931 **
9932 ** <pre>
9933 ** &nbsp; int *pnChangeset,
9934 ** &nbsp; void **ppChangeset,
9935 ** </pre>
9936 **
9937 ** Is replaced by:
9938 **
9939 ** <pre>
9940 ** &nbsp; int (*xOutput)(void *pOut, const void *pData, int nData),
9941 ** &nbsp; void *pOut
9942 ** </pre>
9943 **
9944 ** The xOutput callback is invoked zero or more times to return data to
9945 ** the application. The first parameter passed to each call is a copy of the
9946 ** pOut pointer supplied by the application. The second parameter, pData,
9947 ** points to a buffer nData bytes in size containing the chunk of output
9948 ** data being returned. If the xOutput callback successfully processes the
9949 ** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
9950 ** it should return some other SQLite error code. In this case processing
9951 ** is immediately abandoned and the streaming API function returns a copy
9952 ** of the xOutput error code to the application.
9953 **
9954 ** The sessions module never invokes an xOutput callback with the third
9955 ** parameter set to a value less than or equal to zero. Other than this,
9956 ** no guarantees are made as to the size of the chunks of data returned.
9957 */
9958 int sqlite3changeset_apply_strm(
9959  sqlite3 *db, /* Apply change to "main" db of this handle */
9960  int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
9961  void *pIn, /* First arg for xInput */
9962  int(*xFilter)(
9963  void *pCtx, /* Copy of sixth arg to _apply() */
9964  const char *zTab /* Table name */
9965  ),
9966  int(*xConflict)(
9967  void *pCtx, /* Copy of sixth arg to _apply() */
9968  int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
9969  sqlite3_changeset_iter *p /* Handle describing change and conflict */
9970  ),
9971  void *pCtx /* First argument passed to xConflict */
9972 );
9973 int sqlite3changeset_concat_strm(
9974  int (*xInputA)(void *pIn, void *pData, int *pnData),
9975  void *pInA,
9976  int (*xInputB)(void *pIn, void *pData, int *pnData),
9977  void *pInB,
9978  int (*xOutput)(void *pOut, const void *pData, int nData),
9979  void *pOut
9980 );
9981 int sqlite3changeset_invert_strm(
9982  int (*xInput)(void *pIn, void *pData, int *pnData),
9983  void *pIn,
9984  int (*xOutput)(void *pOut, const void *pData, int nData),
9985  void *pOut
9986 );
9987 int sqlite3changeset_start_strm(
9988  sqlite3_changeset_iter **pp,
9989  int (*xInput)(void *pIn, void *pData, int *pnData),
9990  void *pIn
9991 );
9992 int sqlite3session_changeset_strm(
9993  sqlite3_session *pSession,
9994  int (*xOutput)(void *pOut, const void *pData, int nData),
9995  void *pOut
9996 );
9997 int sqlite3session_patchset_strm(
9998  sqlite3_session *pSession,
9999  int (*xOutput)(void *pOut, const void *pData, int nData),
10000  void *pOut
10001 );
10002 int sqlite3changegroup_add_strm(sqlite3_changegroup*,
10003  int (*xInput)(void *pIn, void *pData, int *pnData),
10004  void *pIn
10005 );
10006 int sqlite3changegroup_output_strm(sqlite3_changegroup*,
10007  int (*xOutput)(void *pOut, const void *pData, int nData),
10008  void *pOut
10009 );
10010 
10011 
10012 /*
10013 ** Make sure we can call this stuff from C++.
10014 */
10015 #if 0
10016 }
10017 #endif
10018 
10019 #endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
10020 
10021 /******** End of sqlite3session.h *********/
10022 /******** Begin file fts5.h *********/
10023 /*
10024 ** 2014 May 31
10025 **
10026 ** The author disclaims copyright to this source code. In place of
10027 ** a legal notice, here is a blessing:
10028 **
10029 ** May you do good and not evil.
10030 ** May you find forgiveness for yourself and forgive others.
10031 ** May you share freely, never taking more than you give.
10032 **
10033 ******************************************************************************
10034 **
10035 ** Interfaces to extend FTS5. Using the interfaces defined in this file,
10036 ** FTS5 may be extended with:
10037 **
10038 ** * custom tokenizers, and
10039 ** * custom auxiliary functions.
10040 */
10041 
10042 
10043 #ifndef _FTS5_H
10044 #define _FTS5_H
10045 
10046 
10047 #if 0
10048 extern "C" {
10049 #endif
10050 
10051 /*************************************************************************
10052 ** CUSTOM AUXILIARY FUNCTIONS
10053 **
10054 ** Virtual table implementations may overload SQL functions by implementing
10055 ** the sqlite3_module.xFindFunction() method.
10056 */
10057 
10058 typedef struct Fts5ExtensionApi Fts5ExtensionApi;
10059 typedef struct Fts5Context Fts5Context;
10060 typedef struct Fts5PhraseIter Fts5PhraseIter;
10061 
10062 typedef void (*fts5_extension_function)(
10063  const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
10064  Fts5Context *pFts, /* First arg to pass to pApi functions */
10065  sqlite3_context *pCtx, /* Context for returning result/error */
10066  int nVal, /* Number of values in apVal[] array */
10067  sqlite3_value **apVal /* Array of trailing arguments */
10068 );
10069 
10070 struct Fts5PhraseIter {
10071  const unsigned char *a;
10072  const unsigned char *b;
10073 };
10074 
10075 /*
10076 ** EXTENSION API FUNCTIONS
10077 **
10078 ** xUserData(pFts):
10079 ** Return a copy of the context pointer the extension function was
10080 ** registered with.
10081 **
10082 ** xColumnTotalSize(pFts, iCol, pnToken):
10083 ** If parameter iCol is less than zero, set output variable *pnToken
10084 ** to the total number of tokens in the FTS5 table. Or, if iCol is
10085 ** non-negative but less than the number of columns in the table, return
10086 ** the total number of tokens in column iCol, considering all rows in
10087 ** the FTS5 table.
10088 **
10089 ** If parameter iCol is greater than or equal to the number of columns
10090 ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
10091 ** an OOM condition or IO error), an appropriate SQLite error code is
10092 ** returned.
10093 **
10094 ** xColumnCount(pFts):
10095 ** Return the number of columns in the table.
10096 **
10097 ** xColumnSize(pFts, iCol, pnToken):
10098 ** If parameter iCol is less than zero, set output variable *pnToken
10099 ** to the total number of tokens in the current row. Or, if iCol is
10100 ** non-negative but less than the number of columns in the table, set
10101 ** *pnToken to the number of tokens in column iCol of the current row.
10102 **
10103 ** If parameter iCol is greater than or equal to the number of columns
10104 ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
10105 ** an OOM condition or IO error), an appropriate SQLite error code is
10106 ** returned.
10107 **
10108 ** This function may be quite inefficient if used with an FTS5 table
10109 ** created with the "columnsize=0" option.
10110 **
10111 ** xColumnText:
10112 ** This function attempts to retrieve the text of column iCol of the
10113 ** current document. If successful, (*pz) is set to point to a buffer
10114 ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
10115 ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
10116 ** if an error occurs, an SQLite error code is returned and the final values
10117 ** of (*pz) and (*pn) are undefined.
10118 **
10119 ** xPhraseCount:
10120 ** Returns the number of phrases in the current query expression.
10121 **
10122 ** xPhraseSize:
10123 ** Returns the number of tokens in phrase iPhrase of the query. Phrases
10124 ** are numbered starting from zero.
10125 **
10126 ** xInstCount:
10127 ** Set *pnInst to the total number of occurrences of all phrases within
10128 ** the query within the current row. Return SQLITE_OK if successful, or
10129 ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
10130 **
10131 ** This API can be quite slow if used with an FTS5 table created with the
10132 ** "detail=none" or "detail=column" option. If the FTS5 table is created
10133 ** with either "detail=none" or "detail=column" and "content=" option
10134 ** (i.e. if it is a contentless table), then this API always returns 0.
10135 **
10136 ** xInst:
10137 ** Query for the details of phrase match iIdx within the current row.
10138 ** Phrase matches are numbered starting from zero, so the iIdx argument
10139 ** should be greater than or equal to zero and smaller than the value
10140 ** output by xInstCount().
10141 **
10142 ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
10143 ** to the column in which it occurs and *piOff the token offset of the
10144 ** first token of the phrase. The exception is if the table was created
10145 ** with the offsets=0 option specified. In this case *piOff is always
10146 ** set to -1.
10147 **
10148 ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
10149 ** if an error occurs.
10150 **
10151 ** This API can be quite slow if used with an FTS5 table created with the
10152 ** "detail=none" or "detail=column" option.
10153 **
10154 ** xRowid:
10155 ** Returns the rowid of the current row.
10156 **
10157 ** xTokenize:
10158 ** Tokenize text using the tokenizer belonging to the FTS5 table.
10159 **
10160 ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
10161 ** This API function is used to query the FTS table for phrase iPhrase
10162 ** of the current query. Specifically, a query equivalent to:
10163 **
10164 ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
10165 **
10166 ** with $p set to a phrase equivalent to the phrase iPhrase of the
10167 ** current query is executed. Any column filter that applies to
10168 ** phrase iPhrase of the current query is included in $p. For each
10169 ** row visited, the callback function passed as the fourth argument
10170 ** is invoked. The context and API objects passed to the callback
10171 ** function may be used to access the properties of each matched row.
10172 ** Invoking Api.xUserData() returns a copy of the pointer passed as
10173 ** the third argument to pUserData.
10174 **
10175 ** If the callback function returns any value other than SQLITE_OK, the
10176 ** query is abandoned and the xQueryPhrase function returns immediately.
10177 ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
10178 ** Otherwise, the error code is propagated upwards.
10179 **
10180 ** If the query runs to completion without incident, SQLITE_OK is returned.
10181 ** Or, if some error occurs before the query completes or is aborted by
10182 ** the callback, an SQLite error code is returned.
10183 **
10184 **
10185 ** xSetAuxdata(pFts5, pAux, xDelete)
10186 **
10187 ** Save the pointer passed as the second argument as the extension functions
10188 ** "auxiliary data". The pointer may then be retrieved by the current or any
10189 ** future invocation of the same fts5 extension function made as part of
10190 ** of the same MATCH query using the xGetAuxdata() API.
10191 **
10192 ** Each extension function is allocated a single auxiliary data slot for
10193 ** each FTS query (MATCH expression). If the extension function is invoked
10194 ** more than once for a single FTS query, then all invocations share a
10195 ** single auxiliary data context.
10196 **
10197 ** If there is already an auxiliary data pointer when this function is
10198 ** invoked, then it is replaced by the new pointer. If an xDelete callback
10199 ** was specified along with the original pointer, it is invoked at this
10200 ** point.
10201 **
10202 ** The xDelete callback, if one is specified, is also invoked on the
10203 ** auxiliary data pointer after the FTS5 query has finished.
10204 **
10205 ** If an error (e.g. an OOM condition) occurs within this function, an
10206 ** the auxiliary data is set to NULL and an error code returned. If the
10207 ** xDelete parameter was not NULL, it is invoked on the auxiliary data
10208 ** pointer before returning.
10209 **
10210 **
10211 ** xGetAuxdata(pFts5, bClear)
10212 **
10213 ** Returns the current auxiliary data pointer for the fts5 extension
10214 ** function. See the xSetAuxdata() method for details.
10215 **
10216 ** If the bClear argument is non-zero, then the auxiliary data is cleared
10217 ** (set to NULL) before this function returns. In this case the xDelete,
10218 ** if any, is not invoked.
10219 **
10220 **
10221 ** xRowCount(pFts5, pnRow)
10222 **
10223 ** This function is used to retrieve the total number of rows in the table.
10224 ** In other words, the same value that would be returned by:
10225 **
10226 ** SELECT count(*) FROM ftstable;
10227 **
10228 ** xPhraseFirst()
10229 ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
10230 ** method, to iterate through all instances of a single query phrase within
10231 ** the current row. This is the same information as is accessible via the
10232 ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
10233 ** to use, this API may be faster under some circumstances. To iterate
10234 ** through instances of phrase iPhrase, use the following code:
10235 **
10236 ** Fts5PhraseIter iter;
10237 ** int iCol, iOff;
10238 ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
10239 ** iCol>=0;
10240 ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
10241 ** ){
10242 ** // An instance of phrase iPhrase at offset iOff of column iCol
10243 ** }
10244 **
10245 ** The Fts5PhraseIter structure is defined above. Applications should not
10246 ** modify this structure directly - it should only be used as shown above
10247 ** with the xPhraseFirst() and xPhraseNext() API methods (and by
10248 ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
10249 **
10250 ** This API can be quite slow if used with an FTS5 table created with the
10251 ** "detail=none" or "detail=column" option. If the FTS5 table is created
10252 ** with either "detail=none" or "detail=column" and "content=" option
10253 ** (i.e. if it is a contentless table), then this API always iterates
10254 ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
10255 **
10256 ** xPhraseNext()
10257 ** See xPhraseFirst above.
10258 **
10259 ** xPhraseFirstColumn()
10260 ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
10261 ** and xPhraseNext() APIs described above. The difference is that instead
10262 ** of iterating through all instances of a phrase in the current row, these
10263 ** APIs are used to iterate through the set of columns in the current row
10264 ** that contain one or more instances of a specified phrase. For example:
10265 **
10266 ** Fts5PhraseIter iter;
10267 ** int iCol;
10268 ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
10269 ** iCol>=0;
10270 ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
10271 ** ){
10272 ** // Column iCol contains at least one instance of phrase iPhrase
10273 ** }
10274 **
10275 ** This API can be quite slow if used with an FTS5 table created with the
10276 ** "detail=none" option. If the FTS5 table is created with either
10277 ** "detail=none" "content=" option (i.e. if it is a contentless table),
10278 ** then this API always iterates through an empty set (all calls to
10279 ** xPhraseFirstColumn() set iCol to -1).
10280 **
10281 ** The information accessed using this API and its companion
10282 ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
10283 ** (or xInst/xInstCount). The chief advantage of this API is that it is
10284 ** significantly more efficient than those alternatives when used with
10285 ** "detail=column" tables.
10286 **
10287 ** xPhraseNextColumn()
10288 ** See xPhraseFirstColumn above.
10289 */
10290 struct Fts5ExtensionApi {
10291  int iVersion; /* Currently always set to 3 */
10292 
10293  void *(*xUserData)(Fts5Context*);
10294 
10295  int (*xColumnCount)(Fts5Context*);
10296  int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
10297  int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
10298 
10299  int (*xTokenize)(Fts5Context*,
10300  const char *pText, int nText, /* Text to tokenize */
10301  void *pCtx, /* Context passed to xToken() */
10302  int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
10303  );
10304 
10305  int (*xPhraseCount)(Fts5Context*);
10306  int (*xPhraseSize)(Fts5Context*, int iPhrase);
10307 
10308  int (*xInstCount)(Fts5Context*, int *pnInst);
10309  int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
10310 
10311  sqlite3_int64 (*xRowid)(Fts5Context*);
10312  int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
10313  int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
10314 
10315  int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
10316  int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
10317  );
10318  int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
10319  void *(*xGetAuxdata)(Fts5Context*, int bClear);
10320 
10321  int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
10322  void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
10323 
10324  int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
10325  void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
10326 };
10327 
10328 /*
10329 ** CUSTOM AUXILIARY FUNCTIONS
10330 *************************************************************************/
10331 
10332 /*************************************************************************
10333 ** CUSTOM TOKENIZERS
10334 **
10335 ** Applications may also register custom tokenizer types. A tokenizer
10336 ** is registered by providing fts5 with a populated instance of the
10337 ** following structure. All structure methods must be defined, setting
10338 ** any member of the fts5_tokenizer struct to NULL leads to undefined
10339 ** behaviour. The structure methods are expected to function as follows:
10340 **
10341 ** xCreate:
10342 ** This function is used to allocate and initialize a tokenizer instance.
10343 ** A tokenizer instance is required to actually tokenize text.
10344 **
10345 ** The first argument passed to this function is a copy of the (void*)
10346 ** pointer provided by the application when the fts5_tokenizer object
10347 ** was registered with FTS5 (the third argument to xCreateTokenizer()).
10348 ** The second and third arguments are an array of nul-terminated strings
10349 ** containing the tokenizer arguments, if any, specified following the
10350 ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
10351 ** to create the FTS5 table.
10352 **
10353 ** The final argument is an output variable. If successful, (*ppOut)
10354 ** should be set to point to the new tokenizer handle and SQLITE_OK
10355 ** returned. If an error occurs, some value other than SQLITE_OK should
10356 ** be returned. In this case, fts5 assumes that the final value of *ppOut
10357 ** is undefined.
10358 **
10359 ** xDelete:
10360 ** This function is invoked to delete a tokenizer handle previously
10361 ** allocated using xCreate(). Fts5 guarantees that this function will
10362 ** be invoked exactly once for each successful call to xCreate().
10363 **
10364 ** xTokenize:
10365 ** This function is expected to tokenize the nText byte string indicated
10366 ** by argument pText. pText may or may not be nul-terminated. The first
10367 ** argument passed to this function is a pointer to an Fts5Tokenizer object
10368 ** returned by an earlier call to xCreate().
10369 **
10370 ** The second argument indicates the reason that FTS5 is requesting
10371 ** tokenization of the supplied text. This is always one of the following
10372 ** four values:
10373 **
10374 ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
10375 ** or removed from the FTS table. The tokenizer is being invoked to
10376 ** determine the set of tokens to add to (or delete from) the
10377 ** FTS index.
10378 **
10379 ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
10380 ** against the FTS index. The tokenizer is being called to tokenize
10381 ** a bareword or quoted string specified as part of the query.
10382 **
10383 ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
10384 ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
10385 ** followed by a "*" character, indicating that the last token
10386 ** returned by the tokenizer will be treated as a token prefix.
10387 **
10388 ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
10389 ** satisfy an fts5_api.xTokenize() request made by an auxiliary
10390 ** function. Or an fts5_api.xColumnSize() request made by the same
10391 ** on a columnsize=0 database.
10392 ** </ul>
10393 **
10394 ** For each token in the input string, the supplied callback xToken() must
10395 ** be invoked. The first argument to it should be a copy of the pointer
10396 ** passed as the second argument to xTokenize(). The third and fourth
10397 ** arguments are a pointer to a buffer containing the token text, and the
10398 ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
10399 ** of the first byte of and first byte immediately following the text from
10400 ** which the token is derived within the input.
10401 **
10402 ** The second argument passed to the xToken() callback ("tflags") should
10403 ** normally be set to 0. The exception is if the tokenizer supports
10404 ** synonyms. In this case see the discussion below for details.
10405 **
10406 ** FTS5 assumes the xToken() callback is invoked for each token in the
10407 ** order that they occur within the input text.
10408 **
10409 ** If an xToken() callback returns any value other than SQLITE_OK, then
10410 ** the tokenization should be abandoned and the xTokenize() method should
10411 ** immediately return a copy of the xToken() return value. Or, if the
10412 ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
10413 ** if an error occurs with the xTokenize() implementation itself, it
10414 ** may abandon the tokenization and return any error code other than
10415 ** SQLITE_OK or SQLITE_DONE.
10416 **
10417 ** SYNONYM SUPPORT
10418 **
10419 ** Custom tokenizers may also support synonyms. Consider a case in which a
10420 ** user wishes to query for a phrase such as "first place". Using the
10421 ** built-in tokenizers, the FTS5 query 'first + place' will match instances
10422 ** of "first place" within the document set, but not alternative forms
10423 ** such as "1st place". In some applications, it would be better to match
10424 ** all instances of "first place" or "1st place" regardless of which form
10425 ** the user specified in the MATCH query text.
10426 **
10427 ** There are several ways to approach this in FTS5:
10428 **
10429 ** <ol><li> By mapping all synonyms to a single token. In this case, the
10430 ** In the above example, this means that the tokenizer returns the
10431 ** same token for inputs "first" and "1st". Say that token is in
10432 ** fact "first", so that when the user inserts the document "I won
10433 ** 1st place" entries are added to the index for tokens "i", "won",
10434 ** "first" and "place". If the user then queries for '1st + place',
10435 ** the tokenizer substitutes "first" for "1st" and the query works
10436 ** as expected.
10437 **
10438 ** <li> By adding multiple synonyms for a single term to the FTS index.
10439 ** In this case, when tokenizing query text, the tokenizer may
10440 ** provide multiple synonyms for a single term within the document.
10441 ** FTS5 then queries the index for each synonym individually. For
10442 ** example, faced with the query:
10443 **
10444 ** <codeblock>
10445 ** ... MATCH 'first place'</codeblock>
10446 **
10447 ** the tokenizer offers both "1st" and "first" as synonyms for the
10448 ** first token in the MATCH query and FTS5 effectively runs a query
10449 ** similar to:
10450 **
10451 ** <codeblock>
10452 ** ... MATCH '(first OR 1st) place'</codeblock>
10453 **
10454 ** except that, for the purposes of auxiliary functions, the query
10455 ** still appears to contain just two phrases - "(first OR 1st)"
10456 ** being treated as a single phrase.
10457 **
10458 ** <li> By adding multiple synonyms for a single term to the FTS index.
10459 ** Using this method, when tokenizing document text, the tokenizer
10460 ** provides multiple synonyms for each token. So that when a
10461 ** document such as "I won first place" is tokenized, entries are
10462 ** added to the FTS index for "i", "won", "first", "1st" and
10463 ** "place".
10464 **
10465 ** This way, even if the tokenizer does not provide synonyms
10466 ** when tokenizing query text (it should not - to do would be
10467 ** inefficient), it doesn't matter if the user queries for
10468 ** 'first + place' or '1st + place', as there are entires in the
10469 ** FTS index corresponding to both forms of the first token.
10470 ** </ol>
10471 **
10472 ** Whether it is parsing document or query text, any call to xToken that
10473 ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
10474 ** is considered to supply a synonym for the previous token. For example,
10475 ** when parsing the document "I won first place", a tokenizer that supports
10476 ** synonyms would call xToken() 5 times, as follows:
10477 **
10478 ** <codeblock>
10479 ** xToken(pCtx, 0, "i", 1, 0, 1);
10480 ** xToken(pCtx, 0, "won", 3, 2, 5);
10481 ** xToken(pCtx, 0, "first", 5, 6, 11);
10482 ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
10483 ** xToken(pCtx, 0, "place", 5, 12, 17);
10484 **</codeblock>
10485 **
10486 ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
10487 ** xToken() is called. Multiple synonyms may be specified for a single token
10488 ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
10489 ** There is no limit to the number of synonyms that may be provided for a
10490 ** single token.
10491 **
10492 ** In many cases, method (1) above is the best approach. It does not add
10493 ** extra data to the FTS index or require FTS5 to query for multiple terms,
10494 ** so it is efficient in terms of disk space and query speed. However, it
10495 ** does not support prefix queries very well. If, as suggested above, the
10496 ** token "first" is subsituted for "1st" by the tokenizer, then the query:
10497 **
10498 ** <codeblock>
10499 ** ... MATCH '1s*'</codeblock>
10500 **
10501 ** will not match documents that contain the token "1st" (as the tokenizer
10502 ** will probably not map "1s" to any prefix of "first").
10503 **
10504 ** For full prefix support, method (3) may be preferred. In this case,
10505 ** because the index contains entries for both "first" and "1st", prefix
10506 ** queries such as 'fi*' or '1s*' will match correctly. However, because
10507 ** extra entries are added to the FTS index, this method uses more space
10508 ** within the database.
10509 **
10510 ** Method (2) offers a midpoint between (1) and (3). Using this method,
10511 ** a query such as '1s*' will match documents that contain the literal
10512 ** token "1st", but not "first" (assuming the tokenizer is not able to
10513 ** provide synonyms for prefixes). However, a non-prefix query like '1st'
10514 ** will match against "1st" and "first". This method does not require
10515 ** extra disk space, as no extra entries are added to the FTS index.
10516 ** On the other hand, it may require more CPU cycles to run MATCH queries,
10517 ** as separate queries of the FTS index are required for each synonym.
10518 **
10519 ** When using methods (2) or (3), it is important that the tokenizer only
10520 ** provide synonyms when tokenizing document text (method (2)) or query
10521 ** text (method (3)), not both. Doing so will not cause any errors, but is
10522 ** inefficient.
10523 */
10524 typedef struct Fts5Tokenizer Fts5Tokenizer;
10525 typedef struct fts5_tokenizer fts5_tokenizer;
10526 struct fts5_tokenizer {
10527  int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
10528  void (*xDelete)(Fts5Tokenizer*);
10529  int (*xTokenize)(Fts5Tokenizer*,
10530  void *pCtx,
10531  int flags, /* Mask of FTS5_TOKENIZE_* flags */
10532  const char *pText, int nText,
10533  int (*xToken)(
10534  void *pCtx, /* Copy of 2nd argument to xTokenize() */
10535  int tflags, /* Mask of FTS5_TOKEN_* flags */
10536  const char *pToken, /* Pointer to buffer containing token */
10537  int nToken, /* Size of token in bytes */
10538  int iStart, /* Byte offset of token within input text */
10539  int iEnd /* Byte offset of end of token within input text */
10540  )
10541  );
10542 };
10543 
10544 /* Flags that may be passed as the third argument to xTokenize() */
10545 #define FTS5_TOKENIZE_QUERY 0x0001
10546 #define FTS5_TOKENIZE_PREFIX 0x0002
10547 #define FTS5_TOKENIZE_DOCUMENT 0x0004
10548 #define FTS5_TOKENIZE_AUX 0x0008
10549 
10550 /* Flags that may be passed by the tokenizer implementation back to FTS5
10551 ** as the third argument to the supplied xToken callback. */
10552 #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
10553 
10554 /*
10555 ** END OF CUSTOM TOKENIZERS
10556 *************************************************************************/
10557 
10558 /*************************************************************************
10559 ** FTS5 EXTENSION REGISTRATION API
10560 */
10561 typedef struct fts5_api fts5_api;
10562 struct fts5_api {
10563  int iVersion; /* Currently always set to 2 */
10564 
10565  /* Create a new tokenizer */
10566  int (*xCreateTokenizer)(
10567  fts5_api *pApi,
10568  const char *zName,
10569  void *pContext,
10570  fts5_tokenizer *pTokenizer,
10571  void (*xDestroy)(void*)
10572  );
10573 
10574  /* Find an existing tokenizer */
10575  int (*xFindTokenizer)(
10576  fts5_api *pApi,
10577  const char *zName,
10578  void **ppContext,
10579  fts5_tokenizer *pTokenizer
10580  );
10581 
10582  /* Create a new auxiliary function */
10583  int (*xCreateFunction)(
10584  fts5_api *pApi,
10585  const char *zName,
10586  void *pContext,
10587  fts5_extension_function xFunction,
10588  void (*xDestroy)(void*)
10589  );
10590 };
10591 
10592 /*
10593 ** END OF REGISTRATION API
10594 *************************************************************************/
10595 
10596 #if 0
10597 } /* end of the 'extern "C"' block */
10598 #endif
10599 
10600 #endif /* _FTS5_H */
10601 
10602 /******** End of fts5.h *********/
10603 
10604 /************** End of sqlite3.h *********************************************/
10605 /************** Continuing where we left off in sqliteInt.h ******************/
10606 
10607 /*
10608 ** Include the configuration header output by 'configure' if we're using the
10609 ** autoconf-based build
10610 */
10611 #ifdef _HAVE_SQLITE_CONFIG_H
10612 #include "config.h"
10613 #endif
10614 
10615 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
10616 /************** Begin file sqliteLimit.h *************************************/
10617 /*
10618 ** 2007 May 7
10619 **
10620 ** The author disclaims copyright to this source code. In place of
10621 ** a legal notice, here is a blessing:
10622 **
10623 ** May you do good and not evil.
10624 ** May you find forgiveness for yourself and forgive others.
10625 ** May you share freely, never taking more than you give.
10626 **
10627 *************************************************************************
10628 **
10629 ** This file defines various limits of what SQLite can process.
10630 */
10631 
10632 /*
10633 ** The maximum length of a TEXT or BLOB in bytes. This also
10634 ** limits the size of a row in a table or index.
10635 **
10636 ** The hard limit is the ability of a 32-bit signed integer
10637 ** to count the size: 2^31-1 or 2147483647.
10638 */
10639 #ifndef SQLITE_MAX_LENGTH
10640 # define SQLITE_MAX_LENGTH 1000000000
10641 #endif
10642 
10643 /*
10644 ** This is the maximum number of
10645 **
10646 ** * Columns in a table
10647 ** * Columns in an index
10648 ** * Columns in a view
10649 ** * Terms in the SET clause of an UPDATE statement
10650 ** * Terms in the result set of a SELECT statement
10651 ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
10652 ** * Terms in the VALUES clause of an INSERT statement
10653 **
10654 ** The hard upper limit here is 32676. Most database people will
10655 ** tell you that in a well-normalized database, you usually should
10656 ** not have more than a dozen or so columns in any table. And if
10657 ** that is the case, there is no point in having more than a few
10658 ** dozen values in any of the other situations described above.
10659 */
10660 #ifndef SQLITE_MAX_COLUMN
10661 # define SQLITE_MAX_COLUMN 2000
10662 #endif
10663 
10664 /*
10665 ** The maximum length of a single SQL statement in bytes.
10666 **
10667 ** It used to be the case that setting this value to zero would
10668 ** turn the limit off. That is no longer true. It is not possible
10669 ** to turn this limit off.
10670 */
10671 #ifndef SQLITE_MAX_SQL_LENGTH
10672 # define SQLITE_MAX_SQL_LENGTH 1000000000
10673 #endif
10674 
10675 /*
10676 ** The maximum depth of an expression tree. This is limited to
10677 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
10678 ** want to place more severe limits on the complexity of an
10679 ** expression.
10680 **
10681 ** A value of 0 used to mean that the limit was not enforced.
10682 ** But that is no longer true. The limit is now strictly enforced
10683 ** at all times.
10684 */
10685 #ifndef SQLITE_MAX_EXPR_DEPTH
10686 # define SQLITE_MAX_EXPR_DEPTH 1000
10687 #endif
10688 
10689 /*
10690 ** The maximum number of terms in a compound SELECT statement.
10691 ** The code generator for compound SELECT statements does one
10692 ** level of recursion for each term. A stack overflow can result
10693 ** if the number of terms is too large. In practice, most SQL
10694 ** never has more than 3 or 4 terms. Use a value of 0 to disable
10695 ** any limit on the number of terms in a compount SELECT.
10696 */
10697 #ifndef SQLITE_MAX_COMPOUND_SELECT
10698 # define SQLITE_MAX_COMPOUND_SELECT 500
10699 #endif
10700 
10701 /*
10702 ** The maximum number of opcodes in a VDBE program.
10703 ** Not currently enforced.
10704 */
10705 #ifndef SQLITE_MAX_VDBE_OP
10706 # define SQLITE_MAX_VDBE_OP 25000
10707 #endif
10708 
10709 /*
10710 ** The maximum number of arguments to an SQL function.
10711 */
10712 #ifndef SQLITE_MAX_FUNCTION_ARG
10713 # define SQLITE_MAX_FUNCTION_ARG 127
10714 #endif
10715 
10716 /*
10717 ** The suggested maximum number of in-memory pages to use for
10718 ** the main database table and for temporary tables.
10719 **
10720 ** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
10721 ** which means the cache size is limited to 2048000 bytes of memory.
10722 ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
10723 ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
10724 */
10725 #ifndef SQLITE_DEFAULT_CACHE_SIZE
10726 # define SQLITE_DEFAULT_CACHE_SIZE -2000
10727 #endif
10728 
10729 /*
10730 ** The default number of frames to accumulate in the log file before
10731 ** checkpointing the database in WAL mode.
10732 */
10733 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
10734 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
10735 #endif
10736 
10737 /*
10738 ** The maximum number of attached databases. This must be between 0
10739 ** and 125. The upper bound of 125 is because the attached databases are
10740 ** counted using a signed 8-bit integer which has a maximum value of 127
10741 ** and we have to allow 2 extra counts for the "main" and "temp" databases.
10742 */
10743 #ifndef SQLITE_MAX_ATTACHED
10744 # define SQLITE_MAX_ATTACHED 10
10745 #endif
10746 
10747 
10748 /*
10749 ** The maximum value of a ?nnn wildcard that the parser will accept.
10750 */
10751 #ifndef SQLITE_MAX_VARIABLE_NUMBER
10752 # define SQLITE_MAX_VARIABLE_NUMBER 999
10753 #endif
10754 
10755 /* Maximum page size. The upper bound on this value is 65536. This a limit
10756 ** imposed by the use of 16-bit offsets within each page.
10757 **
10758 ** Earlier versions of SQLite allowed the user to change this value at
10759 ** compile time. This is no longer permitted, on the grounds that it creates
10760 ** a library that is technically incompatible with an SQLite library
10761 ** compiled with a different limit. If a process operating on a database
10762 ** with a page-size of 65536 bytes crashes, then an instance of SQLite
10763 ** compiled with the default page-size limit will not be able to rollback
10764 ** the aborted transaction. This could lead to database corruption.
10765 */
10766 #ifdef SQLITE_MAX_PAGE_SIZE
10767 # undef SQLITE_MAX_PAGE_SIZE
10768 #endif
10769 #define SQLITE_MAX_PAGE_SIZE 65536
10770 
10771 
10772 /*
10773 ** The default size of a database page.
10774 */
10775 #ifndef SQLITE_DEFAULT_PAGE_SIZE
10776 # define SQLITE_DEFAULT_PAGE_SIZE 4096
10777 #endif
10778 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
10779 # undef SQLITE_DEFAULT_PAGE_SIZE
10780 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
10781 #endif
10782 
10783 /*
10784 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
10785 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
10786 ** device characteristics (sector-size and atomic write() support),
10787 ** SQLite may choose a larger value. This constant is the maximum value
10788 ** SQLite will choose on its own.
10789 */
10790 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
10791 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
10792 #endif
10793 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
10794 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
10795 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
10796 #endif
10797 
10798 
10799 /*
10800 ** Maximum number of pages in one database file.
10801 **
10802 ** This is really just the default value for the max_page_count pragma.
10803 ** This value can be lowered (or raised) at run-time using that the
10804 ** max_page_count macro.
10805 */
10806 #ifndef SQLITE_MAX_PAGE_COUNT
10807 # define SQLITE_MAX_PAGE_COUNT 1073741823
10808 #endif
10809 
10810 /*
10811 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
10812 ** operator.
10813 */
10814 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
10815 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
10816 #endif
10817 
10818 /*
10819 ** Maximum depth of recursion for triggers.
10820 **
10821 ** A value of 1 means that a trigger program will not be able to itself
10822 ** fire any triggers. A value of 0 means that no trigger programs at all
10823 ** may be executed.
10824 */
10825 #ifndef SQLITE_MAX_TRIGGER_DEPTH
10826 # define SQLITE_MAX_TRIGGER_DEPTH 1000
10827 #endif
10828 
10829 /************** End of sqliteLimit.h *****************************************/
10830 /************** Continuing where we left off in sqliteInt.h ******************/
10831 
10832 /* Disable nuisance warnings on Borland compilers */
10833 #if defined(__BORLANDC__)
10834 #pragma warn -rch /* unreachable code */
10835 #pragma warn -ccc /* Condition is always true or false */
10836 #pragma warn -aus /* Assigned value is never used */
10837 #pragma warn -csu /* Comparing signed and unsigned */
10838 #pragma warn -spa /* Suspicious pointer arithmetic */
10839 #endif
10840 
10841 /*
10842 ** Include standard header files as necessary
10843 */
10844 #ifdef HAVE_STDINT_H
10845 #include <stdint.h>
10846 #endif
10847 #ifdef HAVE_INTTYPES_H
10848 #include <inttypes.h>
10849 #endif
10850 
10851 /*
10852 ** The following macros are used to cast pointers to integers and
10853 ** integers to pointers. The way you do this varies from one compiler
10854 ** to the next, so we have developed the following set of #if statements
10855 ** to generate appropriate macros for a wide range of compilers.
10856 **
10857 ** The correct "ANSI" way to do this is to use the intptr_t type.
10858 ** Unfortunately, that typedef is not available on all compilers, or
10859 ** if it is available, it requires an #include of specific headers
10860 ** that vary from one machine to the next.
10861 **
10862 ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
10863 ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
10864 ** So we have to define the macros in different ways depending on the
10865 ** compiler.
10866 */
10867 #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
10868 # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
10869 # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
10870 #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
10871 # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
10872 # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
10873 #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
10874 # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
10875 # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
10876 #else /* Generates a warning - but it always works */
10877 # define SQLITE_INT_TO_PTR(X) ((void*)(X))
10878 # define SQLITE_PTR_TO_INT(X) ((int)(X))
10879 #endif
10880 
10881 /*
10882 ** A macro to hint to the compiler that a function should not be
10883 ** inlined.
10884 */
10885 #if defined(__GNUC__)
10886 # define SQLITE_NOINLINE __attribute__((noinline))
10887 #elif defined(_MSC_VER) && _MSC_VER>=1310
10888 # define SQLITE_NOINLINE __declspec(noinline)
10889 #else
10890 # define SQLITE_NOINLINE
10891 #endif
10892 
10893 /*
10894 ** Make sure that the compiler intrinsics we desire are enabled when
10895 ** compiling with an appropriate version of MSVC unless prevented by
10896 ** the SQLITE_DISABLE_INTRINSIC define.
10897 */
10898 #if !defined(SQLITE_DISABLE_INTRINSIC)
10899 # if defined(_MSC_VER) && _MSC_VER>=1400
10900 # if !defined(_WIN32_WCE)
10901 # include <intrin.h>
10902 # pragma intrinsic(_byteswap_ushort)
10903 # pragma intrinsic(_byteswap_ulong)
10904 # pragma intrinsic(_ReadWriteBarrier)
10905 # else
10906 # include <cmnintrin.h>
10907 # endif
10908 # endif
10909 #endif
10910 
10911 /*
10912 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
10913 ** 0 means mutexes are permanently disable and the library is never
10914 ** threadsafe. 1 means the library is serialized which is the highest
10915 ** level of threadsafety. 2 means the library is multithreaded - multiple
10916 ** threads can use SQLite as long as no two threads try to use the same
10917 ** database connection at the same time.
10918 **
10919 ** Older versions of SQLite used an optional THREADSAFE macro.
10920 ** We support that for legacy.
10921 */
10922 #if !defined(SQLITE_THREADSAFE)
10923 # if defined(THREADSAFE)
10924 # define SQLITE_THREADSAFE THREADSAFE
10925 # else
10926 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
10927 # endif
10928 #endif
10929 
10930 /*
10931 ** Powersafe overwrite is on by default. But can be turned off using
10932 ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
10933 */
10934 #ifndef SQLITE_POWERSAFE_OVERWRITE
10935 # define SQLITE_POWERSAFE_OVERWRITE 1
10936 #endif
10937 
10938 /*
10939 ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
10940 ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
10941 ** which case memory allocation statistics are disabled by default.
10942 */
10943 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
10944 # define SQLITE_DEFAULT_MEMSTATUS 1
10945 #endif
10946 
10947 /*
10948 ** Exactly one of the following macros must be defined in order to
10949 ** specify which memory allocation subsystem to use.
10950 **
10951 ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
10952 ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
10953 ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
10954 ** SQLITE_MEMDEBUG // Debugging version of system malloc()
10955 **
10956 ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
10957 ** assert() macro is enabled, each call into the Win32 native heap subsystem
10958 ** will cause HeapValidate to be called. If heap validation should fail, an
10959 ** assertion will be triggered.
10960 **
10961 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
10962 ** the default.
10963 */
10964 #if defined(SQLITE_SYSTEM_MALLOC) \
10965  + defined(SQLITE_WIN32_MALLOC) \
10966  + defined(SQLITE_ZERO_MALLOC) \
10967  + defined(SQLITE_MEMDEBUG)>1
10968 # error "Two or more of the following compile-time configuration options\
10969  are defined but at most one is allowed:\
10970  SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
10971  SQLITE_ZERO_MALLOC"
10972 #endif
10973 #if defined(SQLITE_SYSTEM_MALLOC) \
10974  + defined(SQLITE_WIN32_MALLOC) \
10975  + defined(SQLITE_ZERO_MALLOC) \
10976  + defined(SQLITE_MEMDEBUG)==0
10977 # define SQLITE_SYSTEM_MALLOC 1
10978 #endif
10979 
10980 /*
10981 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
10982 ** sizes of memory allocations below this value where possible.
10983 */
10984 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
10985 # define SQLITE_MALLOC_SOFT_LIMIT 1024
10986 #endif
10987 
10988 /*
10989 ** We need to define _XOPEN_SOURCE as follows in order to enable
10990 ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
10991 ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
10992 ** it.
10993 */
10994 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
10995 # define _XOPEN_SOURCE 600
10996 #endif
10997 
10998 /*
10999 ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
11000 ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
11001 ** make it true by defining or undefining NDEBUG.
11002 **
11003 ** Setting NDEBUG makes the code smaller and faster by disabling the
11004 ** assert() statements in the code. So we want the default action
11005 ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
11006 ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
11007 ** feature.
11008 */
11009 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
11010 # define NDEBUG 1
11011 #endif
11012 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
11013 # undef NDEBUG
11014 #endif
11015 
11016 /*
11017 ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
11018 */
11019 #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
11020 # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
11021 #endif
11022 
11023 /*
11024 ** The testcase() macro is used to aid in coverage testing. When
11025 ** doing coverage testing, the condition inside the argument to
11026 ** testcase() must be evaluated both true and false in order to
11027 ** get full branch coverage. The testcase() macro is inserted
11028 ** to help ensure adequate test coverage in places where simple
11029 ** condition/decision coverage is inadequate. For example, testcase()
11030 ** can be used to make sure boundary values are tested. For
11031 ** bitmask tests, testcase() can be used to make sure each bit
11032 ** is significant and used at least once. On switch statements
11033 ** where multiple cases go to the same block of code, testcase()
11034 ** can insure that all cases are evaluated.
11035 **
11036 */
11037 #ifdef SQLITE_COVERAGE_TEST
11038 SQLITE_PRIVATE void sqlite3Coverage(int);
11039 # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
11040 #else
11041 # define testcase(X)
11042 #endif
11043 
11044 /*
11045 ** The TESTONLY macro is used to enclose variable declarations or
11046 ** other bits of code that are needed to support the arguments
11047 ** within testcase() and assert() macros.
11048 */
11049 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
11050 # define TESTONLY(X) X
11051 #else
11052 # define TESTONLY(X)
11053 #endif
11054 
11055 /*
11056 ** Sometimes we need a small amount of code such as a variable initialization
11057 ** to setup for a later assert() statement. We do not want this code to
11058 ** appear when assert() is disabled. The following macro is therefore
11059 ** used to contain that setup code. The "VVA" acronym stands for
11060 ** "Verification, Validation, and Accreditation". In other words, the
11061 ** code within VVA_ONLY() will only run during verification processes.
11062 */
11063 #ifndef NDEBUG
11064 # define VVA_ONLY(X) X
11065 #else
11066 # define VVA_ONLY(X)
11067 #endif
11068 
11069 /*
11070 ** The ALWAYS and NEVER macros surround boolean expressions which
11071 ** are intended to always be true or false, respectively. Such
11072 ** expressions could be omitted from the code completely. But they
11073 ** are included in a few cases in order to enhance the resilience
11074 ** of SQLite to unexpected behavior - to make the code "self-healing"
11075 ** or "ductile" rather than being "brittle" and crashing at the first
11076 ** hint of unplanned behavior.
11077 **
11078 ** In other words, ALWAYS and NEVER are added for defensive code.
11079 **
11080 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
11081 ** be true and false so that the unreachable code they specify will
11082 ** not be counted as untested code.
11083 */
11084 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
11085 # define ALWAYS(X) (1)
11086 # define NEVER(X) (0)
11087 #elif !defined(NDEBUG)
11088 # define ALWAYS(X) ((X)?1:(assert(0),0))
11089 # define NEVER(X) ((X)?(assert(0),1):0)
11090 #else
11091 # define ALWAYS(X) (X)
11092 # define NEVER(X) (X)
11093 #endif
11094 
11095 /*
11096 ** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
11097 ** defined. We need to defend against those failures when testing with
11098 ** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
11099 ** during a normal build. The following macro can be used to disable tests
11100 ** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
11101 */
11102 #if defined(SQLITE_TEST_REALLOC_STRESS)
11103 # define ONLY_IF_REALLOC_STRESS(X) (X)
11104 #elif !defined(NDEBUG)
11105 # define ONLY_IF_REALLOC_STRESS(X) ((X)?(assert(0),1):0)
11106 #else
11107 # define ONLY_IF_REALLOC_STRESS(X) (0)
11108 #endif
11109 
11110 /*
11111 ** Declarations used for tracing the operating system interfaces.
11112 */
11113 #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
11114  (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
11115  extern int sqlite3OSTrace;
11116 # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
11117 # define SQLITE_HAVE_OS_TRACE
11118 #else
11119 # define OSTRACE(X)
11120 # undef SQLITE_HAVE_OS_TRACE
11121 #endif
11122 
11123 /*
11124 ** Is the sqlite3ErrName() function needed in the build? Currently,
11125 ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
11126 ** OSTRACE is enabled), and by several "test*.c" files (which are
11127 ** compiled using SQLITE_TEST).
11128 */
11129 #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
11130  (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
11131 # define SQLITE_NEED_ERR_NAME
11132 #else
11133 # undef SQLITE_NEED_ERR_NAME
11134 #endif
11135 
11136 /*
11137 ** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
11138 */
11139 #ifdef SQLITE_OMIT_EXPLAIN
11140 # undef SQLITE_ENABLE_EXPLAIN_COMMENTS
11141 #endif
11142 
11143 /*
11144 ** Return true (non-zero) if the input is an integer that is too large
11145 ** to fit in 32-bits. This macro is used inside of various testcase()
11146 ** macros to verify that we have tested SQLite for large-file support.
11147 */
11148 #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
11149 
11150 /*
11151 ** The macro unlikely() is a hint that surrounds a boolean
11152 ** expression that is usually false. Macro likely() surrounds
11153 ** a boolean expression that is usually true. These hints could,
11154 ** in theory, be used by the compiler to generate better code, but
11155 ** currently they are just comments for human readers.
11156 */
11157 #define likely(X) (X)
11158 #define unlikely(X) (X)
11159 
11160 /************** Include hash.h in the middle of sqliteInt.h ******************/
11161 /************** Begin file hash.h ********************************************/
11162 /*
11163 ** 2001 September 22
11164 **
11165 ** The author disclaims copyright to this source code. In place of
11166 ** a legal notice, here is a blessing:
11167 **
11168 ** May you do good and not evil.
11169 ** May you find forgiveness for yourself and forgive others.
11170 ** May you share freely, never taking more than you give.
11171 **
11172 *************************************************************************
11173 ** This is the header file for the generic hash-table implementation
11174 ** used in SQLite.
11175 */
11176 #ifndef SQLITE_HASH_H
11177 #define SQLITE_HASH_H
11178 
11179 /* Forward declarations of structures. */
11180 typedef struct Hash Hash;
11181 typedef struct HashElem HashElem;
11182 
11183 /* A complete hash table is an instance of the following structure.
11184 ** The internals of this structure are intended to be opaque -- client
11185 ** code should not attempt to access or modify the fields of this structure
11186 ** directly. Change this structure only by using the routines below.
11187 ** However, some of the "procedures" and "functions" for modifying and
11188 ** accessing this structure are really macros, so we can't really make
11189 ** this structure opaque.
11190 **
11191 ** All elements of the hash table are on a single doubly-linked list.
11192 ** Hash.first points to the head of this list.
11193 **
11194 ** There are Hash.htsize buckets. Each bucket points to a spot in
11195 ** the global doubly-linked list. The contents of the bucket are the
11196 ** element pointed to plus the next _ht.count-1 elements in the list.
11197 **
11198 ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
11199 ** by a linear search of the global list. For small tables, the
11200 ** Hash.ht table is never allocated because if there are few elements
11201 ** in the table, it is faster to do a linear search than to manage
11202 ** the hash table.
11203 */
11204 struct Hash {
11205  unsigned int htsize; /* Number of buckets in the hash table */
11206  unsigned int count; /* Number of entries in this table */
11207  HashElem *first; /* The first element of the array */
11208  struct _ht { /* the hash table */
11209  int count; /* Number of entries with this hash */
11210  HashElem *chain; /* Pointer to first entry with this hash */
11211  } *ht;
11212 };
11213 
11214 /* Each element in the hash table is an instance of the following
11215 ** structure. All elements are stored on a single doubly-linked list.
11216 **
11217 ** Again, this structure is intended to be opaque, but it can't really
11218 ** be opaque because it is used by macros.
11219 */
11220 struct HashElem {
11221  HashElem *next, *prev; /* Next and previous elements in the table */
11222  void *data; /* Data associated with this element */
11223  const char *pKey; /* Key associated with this element */
11224 };
11225 
11226 /*
11227 ** Access routines. To delete, insert a NULL pointer.
11228 */
11229 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
11230 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
11231 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
11232 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
11233 
11234 /*
11235 ** Macros for looping over all elements of a hash table. The idiom is
11236 ** like this:
11237 **
11238 ** Hash h;
11239 ** HashElem *p;
11240 ** ...
11241 ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
11242 ** SomeStructure *pData = sqliteHashData(p);
11243 ** // do something with pData
11244 ** }
11245 */
11246 #define sqliteHashFirst(H) ((H)->first)
11247 #define sqliteHashNext(E) ((E)->next)
11248 #define sqliteHashData(E) ((E)->data)
11249 /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
11250 /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
11251 
11252 /*
11253 ** Number of entries in a hash table
11254 */
11255 /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
11256 
11257 #endif /* SQLITE_HASH_H */
11258 
11259 /************** End of hash.h ************************************************/
11260 /************** Continuing where we left off in sqliteInt.h ******************/
11261 /************** Include parse.h in the middle of sqliteInt.h *****************/
11262 /************** Begin file parse.h *******************************************/
11263 #define TK_SEMI 1
11264 #define TK_EXPLAIN 2
11265 #define TK_QUERY 3
11266 #define TK_PLAN 4
11267 #define TK_BEGIN 5
11268 #define TK_TRANSACTION 6
11269 #define TK_DEFERRED 7
11270 #define TK_IMMEDIATE 8
11271 #define TK_EXCLUSIVE 9
11272 #define TK_COMMIT 10
11273 #define TK_END 11
11274 #define TK_ROLLBACK 12
11275 #define TK_SAVEPOINT 13
11276 #define TK_RELEASE 14
11277 #define TK_TO 15
11278 #define TK_TABLE 16
11279 #define TK_CREATE 17
11280 #define TK_IF 18
11281 #define TK_NOT 19
11282 #define TK_EXISTS 20
11283 #define TK_TEMP 21
11284 #define TK_LP 22
11285 #define TK_RP 23
11286 #define TK_AS 24
11287 #define TK_WITHOUT 25
11288 #define TK_COMMA 26
11289 #define TK_OR 27
11290 #define TK_AND 28
11291 #define TK_IS 29
11292 #define TK_MATCH 30
11293 #define TK_LIKE_KW 31
11294 #define TK_BETWEEN 32
11295 #define TK_IN 33
11296 #define TK_ISNULL 34
11297 #define TK_NOTNULL 35
11298 #define TK_NE 36
11299 #define TK_EQ 37
11300 #define TK_GT 38
11301 #define TK_LE 39
11302 #define TK_LT 40
11303 #define TK_GE 41
11304 #define TK_ESCAPE 42
11305 #define TK_BITAND 43
11306 #define TK_BITOR 44
11307 #define TK_LSHIFT 45
11308 #define TK_RSHIFT 46
11309 #define TK_PLUS 47
11310 #define TK_MINUS 48
11311 #define TK_STAR 49
11312 #define TK_SLASH 50
11313 #define TK_REM 51
11314 #define TK_CONCAT 52
11315 #define TK_COLLATE 53
11316 #define TK_BITNOT 54
11317 #define TK_ID 55
11318 #define TK_INDEXED 56
11319 #define TK_ABORT 57
11320 #define TK_ACTION 58
11321 #define TK_AFTER 59
11322 #define TK_ANALYZE 60
11323 #define TK_ASC 61
11324 #define TK_ATTACH 62
11325 #define TK_BEFORE 63
11326 #define TK_BY 64
11327 #define TK_CASCADE 65
11328 #define TK_CAST 66
11329 #define TK_COLUMNKW 67
11330 #define TK_CONFLICT 68
11331 #define TK_DATABASE 69
11332 #define TK_DESC 70
11333 #define TK_DETACH 71
11334 #define TK_EACH 72
11335 #define TK_FAIL 73
11336 #define TK_FOR 74
11337 #define TK_IGNORE 75
11338 #define TK_INITIALLY 76
11339 #define TK_INSTEAD 77
11340 #define TK_NO 78
11341 #define TK_KEY 79
11342 #define TK_OF 80
11343 #define TK_OFFSET 81
11344 #define TK_PRAGMA 82
11345 #define TK_RAISE 83
11346 #define TK_RECURSIVE 84
11347 #define TK_REPLACE 85
11348 #define TK_RESTRICT 86
11349 #define TK_ROW 87
11350 #define TK_TRIGGER 88
11351 #define TK_VACUUM 89
11352 #define TK_VIEW 90
11353 #define TK_VIRTUAL 91
11354 #define TK_WITH 92
11355 #define TK_REINDEX 93
11356 #define TK_RENAME 94
11357 #define TK_CTIME_KW 95
11358 #define TK_ANY 96
11359 #define TK_STRING 97
11360 #define TK_JOIN_KW 98
11361 #define TK_CONSTRAINT 99
11362 #define TK_DEFAULT 100
11363 #define TK_NULL 101
11364 #define TK_PRIMARY 102
11365 #define TK_UNIQUE 103
11366 #define TK_CHECK 104
11367 #define TK_REFERENCES 105
11368 #define TK_AUTOINCR 106
11369 #define TK_ON 107
11370 #define TK_INSERT 108
11371 #define TK_DELETE 109
11372 #define TK_UPDATE 110
11373 #define TK_SET 111
11374 #define TK_DEFERRABLE 112
11375 #define TK_FOREIGN 113
11376 #define TK_DROP 114
11377 #define TK_UNION 115
11378 #define TK_ALL 116
11379 #define TK_EXCEPT 117
11380 #define TK_INTERSECT 118
11381 #define TK_SELECT 119
11382 #define TK_VALUES 120
11383 #define TK_DISTINCT 121
11384 #define TK_DOT 122
11385 #define TK_FROM 123
11386 #define TK_JOIN 124
11387 #define TK_USING 125
11388 #define TK_ORDER 126
11389 #define TK_GROUP 127
11390 #define TK_HAVING 128
11391 #define TK_LIMIT 129
11392 #define TK_WHERE 130
11393 #define TK_INTO 131
11394 #define TK_INTEGER 132
11395 #define TK_FLOAT 133
11396 #define TK_BLOB 134
11397 #define TK_VARIABLE 135
11398 #define TK_CASE 136
11399 #define TK_WHEN 137
11400 #define TK_THEN 138
11401 #define TK_ELSE 139
11402 #define TK_INDEX 140
11403 #define TK_ALTER 141
11404 #define TK_ADD 142
11405 #define TK_TO_TEXT 143
11406 #define TK_TO_BLOB 144
11407 #define TK_TO_NUMERIC 145
11408 #define TK_TO_INT 146
11409 #define TK_TO_REAL 147
11410 #define TK_ISNOT 148
11411 #define TK_END_OF_FILE 149
11412 #define TK_UNCLOSED_STRING 150
11413 #define TK_FUNCTION 151
11414 #define TK_COLUMN 152
11415 #define TK_AGG_FUNCTION 153
11416 #define TK_AGG_COLUMN 154
11417 #define TK_UMINUS 155
11418 #define TK_UPLUS 156
11419 #define TK_REGISTER 157
11420 #define TK_ASTERISK 158
11421 #define TK_SPAN 159
11422 #define TK_SPACE 160
11423 #define TK_ILLEGAL 161
11424 
11425 /* The token codes above must all fit in 8 bits */
11426 #define TKFLG_MASK 0xff
11427 
11428 /* Flags that can be added to a token code when it is not
11429 ** being stored in a u8: */
11430 #define TKFLG_DONTFOLD 0x100 /* Omit constant folding optimizations */
11431 
11432 /************** End of parse.h ***********************************************/
11433 /************** Continuing where we left off in sqliteInt.h ******************/
11434 #include <stdio.h>
11435 #include <stdlib.h>
11436 #include <string.h>
11437 #include <assert.h>
11438 #include <stddef.h>
11439 
11440 /*
11441 ** If compiling for a processor that lacks floating point support,
11442 ** substitute integer for floating-point
11443 */
11444 #ifdef SQLITE_OMIT_FLOATING_POINT
11445 # define double sqlite_int64
11446 # define float sqlite_int64
11447 # define LONGDOUBLE_TYPE sqlite_int64
11448 # ifndef SQLITE_BIG_DBL
11449 # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
11450 # endif
11451 # define SQLITE_OMIT_DATETIME_FUNCS 1
11452 # define SQLITE_OMIT_TRACE 1
11453 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
11454 # undef SQLITE_HAVE_ISNAN
11455 #endif
11456 #ifndef SQLITE_BIG_DBL
11457 # define SQLITE_BIG_DBL (1e99)
11458 #endif
11459 
11460 /*
11461 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
11462 ** afterward. Having this macro allows us to cause the C compiler
11463 ** to omit code used by TEMP tables without messy #ifndef statements.
11464 */
11465 #ifdef SQLITE_OMIT_TEMPDB
11466 #define OMIT_TEMPDB 1
11467 #else
11468 #define OMIT_TEMPDB 0
11469 #endif
11470 
11471 /*
11472 ** The "file format" number is an integer that is incremented whenever
11473 ** the VDBE-level file format changes. The following macros define the
11474 ** the default file format for new databases and the maximum file format
11475 ** that the library can read.
11476 */
11477 #define SQLITE_MAX_FILE_FORMAT 4
11478 #ifndef SQLITE_DEFAULT_FILE_FORMAT
11479 # define SQLITE_DEFAULT_FILE_FORMAT 4
11480 #endif
11481 
11482 /*
11483 ** Determine whether triggers are recursive by default. This can be
11484 ** changed at run-time using a pragma.
11485 */
11486 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
11487 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
11488 #endif
11489 
11490 /*
11491 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
11492 ** on the command-line
11493 */
11494 #ifndef SQLITE_TEMP_STORE
11495 # define SQLITE_TEMP_STORE 1
11496 # define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */
11497 #endif
11498 
11499 /*
11500 ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
11501 ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
11502 ** to zero.
11503 */
11504 #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
11505 # undef SQLITE_MAX_WORKER_THREADS
11506 # define SQLITE_MAX_WORKER_THREADS 0
11507 #endif
11508 #ifndef SQLITE_MAX_WORKER_THREADS
11509 # define SQLITE_MAX_WORKER_THREADS 8
11510 #endif
11511 #ifndef SQLITE_DEFAULT_WORKER_THREADS
11512 # define SQLITE_DEFAULT_WORKER_THREADS 0
11513 #endif
11514 #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
11515 # undef SQLITE_MAX_WORKER_THREADS
11516 # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
11517 #endif
11518 
11519 /*
11520 ** The default initial allocation for the pagecache when using separate
11521 ** pagecaches for each database connection. A positive number is the
11522 ** number of pages. A negative number N translations means that a buffer
11523 ** of -1024*N bytes is allocated and used for as many pages as it will hold.
11524 */
11525 #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
11526 # define SQLITE_DEFAULT_PCACHE_INITSZ 100
11527 #endif
11528 
11529 /*
11530 ** GCC does not define the offsetof() macro so we'll have to do it
11531 ** ourselves.
11532 */
11533 #ifndef offsetof
11534 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
11535 #endif
11536 
11537 /*
11538 ** Macros to compute minimum and maximum of two numbers.
11539 */
11540 #ifndef MIN
11541 # define MIN(A,B) ((A)<(B)?(A):(B))
11542 #endif
11543 #ifndef MAX
11544 # define MAX(A,B) ((A)>(B)?(A):(B))
11545 #endif
11546 
11547 /*
11548 ** Swap two objects of type TYPE.
11549 */
11550 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
11551 
11552 /*
11553 ** Check to see if this machine uses EBCDIC. (Yes, believe it or
11554 ** not, there are still machines out there that use EBCDIC.)
11555 */
11556 #if 'A' == '\301'
11557 # define SQLITE_EBCDIC 1
11558 #else
11559 # define SQLITE_ASCII 1
11560 #endif
11561 
11562 /*
11563 ** Integers of known sizes. These typedefs might change for architectures
11564 ** where the sizes very. Preprocessor macros are available so that the
11565 ** types can be conveniently redefined at compile-type. Like this:
11566 **
11567 ** cc '-DUINTPTR_TYPE=long long int' ...
11568 */
11569 #ifndef UINT32_TYPE
11570 # ifdef HAVE_UINT32_T
11571 # define UINT32_TYPE uint32_t
11572 # else
11573 # define UINT32_TYPE unsigned int
11574 # endif
11575 #endif
11576 #ifndef UINT16_TYPE
11577 # ifdef HAVE_UINT16_T
11578 # define UINT16_TYPE uint16_t
11579 # else
11580 # define UINT16_TYPE unsigned short int
11581 # endif
11582 #endif
11583 #ifndef INT16_TYPE
11584 # ifdef HAVE_INT16_T
11585 # define INT16_TYPE int16_t
11586 # else
11587 # define INT16_TYPE short int
11588 # endif
11589 #endif
11590 #ifndef UINT8_TYPE
11591 # ifdef HAVE_UINT8_T
11592 # define UINT8_TYPE uint8_t
11593 # else
11594 # define UINT8_TYPE unsigned char
11595 # endif
11596 #endif
11597 #ifndef INT8_TYPE
11598 # ifdef HAVE_INT8_T
11599 # define INT8_TYPE int8_t
11600 # else
11601 # define INT8_TYPE signed char
11602 # endif
11603 #endif
11604 #ifndef LONGDOUBLE_TYPE
11605 # define LONGDOUBLE_TYPE long double
11606 #endif
11607 typedef sqlite_int64 i64; /* 8-byte signed integer */
11608 typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
11609 typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
11610 typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
11611 typedef INT16_TYPE i16; /* 2-byte signed integer */
11612 typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
11613 typedef INT8_TYPE i8; /* 1-byte signed integer */
11614 
11615 /*
11616 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
11617 ** that can be stored in a u32 without loss of data. The value
11618 ** is 0x00000000ffffffff. But because of quirks of some compilers, we
11619 ** have to specify the value in the less intuitive manner shown:
11620 */
11621 #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
11622 
11623 /*
11624 ** The datatype used to store estimates of the number of rows in a
11625 ** table or index. This is an unsigned integer type. For 99.9% of
11626 ** the world, a 32-bit integer is sufficient. But a 64-bit integer
11627 ** can be used at compile-time if desired.
11628 */
11629 #ifdef SQLITE_64BIT_STATS
11630  typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
11631 #else
11632  typedef u32 tRowcnt; /* 32-bit is the default */
11633 #endif
11634 
11635 /*
11636 ** Estimated quantities used for query planning are stored as 16-bit
11637 ** logarithms. For quantity X, the value stored is 10*log2(X). This
11638 ** gives a possible range of values of approximately 1.0e986 to 1e-986.
11639 ** But the allowed values are "grainy". Not every value is representable.
11640 ** For example, quantities 16 and 17 are both represented by a LogEst
11641 ** of 40. However, since LogEst quantities are suppose to be estimates,
11642 ** not exact values, this imprecision is not a problem.
11643 **
11644 ** "LogEst" is short for "Logarithmic Estimate".
11645 **
11646 ** Examples:
11647 ** 1 -> 0 20 -> 43 10000 -> 132
11648 ** 2 -> 10 25 -> 46 25000 -> 146
11649 ** 3 -> 16 100 -> 66 1000000 -> 199
11650 ** 4 -> 20 1000 -> 99 1048576 -> 200
11651 ** 10 -> 33 1024 -> 100 4294967296 -> 320
11652 **
11653 ** The LogEst can be negative to indicate fractional values.
11654 ** Examples:
11655 **
11656 ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
11657 */
11658 typedef INT16_TYPE LogEst;
11659 
11660 /*
11661 ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
11662 */
11663 #ifndef SQLITE_PTRSIZE
11664 # if defined(__SIZEOF_POINTER__)
11665 # define SQLITE_PTRSIZE __SIZEOF_POINTER__
11666 # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
11667  defined(_M_ARM) || defined(__arm__) || defined(__x86)
11668 # define SQLITE_PTRSIZE 4
11669 # else
11670 # define SQLITE_PTRSIZE 8
11671 # endif
11672 #endif
11673 
11674 /* The uptr type is an unsigned integer large enough to hold a pointer
11675 */
11676 #if defined(HAVE_STDINT_H)
11677  typedef uintptr_t uptr;
11678 #elif SQLITE_PTRSIZE==4
11679  typedef u32 uptr;
11680 #else
11681  typedef u64 uptr;
11682 #endif
11683 
11684 /*
11685 ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
11686 ** something between S (inclusive) and E (exclusive).
11687 **
11688 ** In other words, S is a buffer and E is a pointer to the first byte after
11689 ** the end of buffer S. This macro returns true if P points to something
11690 ** contained within the buffer S.
11691 */
11692 #define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
11693 
11694 
11695 /*
11696 ** Macros to determine whether the machine is big or little endian,
11697 ** and whether or not that determination is run-time or compile-time.
11698 **
11699 ** For best performance, an attempt is made to guess at the byte-order
11700 ** using C-preprocessor macros. If that is unsuccessful, or if
11701 ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
11702 ** at run-time.
11703 */
11704 #if (defined(i386) || defined(__i386__) || defined(_M_IX86) || \
11705  defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
11706  defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
11707  defined(__arm__)) && !defined(SQLITE_RUNTIME_BYTEORDER)
11708 # define SQLITE_BYTEORDER 1234
11709 # define SQLITE_BIGENDIAN 0
11710 # define SQLITE_LITTLEENDIAN 1
11711 # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
11712 #endif
11713 #if (defined(sparc) || defined(__ppc__)) \
11714  && !defined(SQLITE_RUNTIME_BYTEORDER)
11715 # define SQLITE_BYTEORDER 4321
11716 # define SQLITE_BIGENDIAN 1
11717 # define SQLITE_LITTLEENDIAN 0
11718 # define SQLITE_UTF16NATIVE SQLITE_UTF16BE
11719 #endif
11720 #if !defined(SQLITE_BYTEORDER)
11721 # ifdef SQLITE_AMALGAMATION
11722  const int sqlite3one = 1;
11723 # else
11724  extern const int sqlite3one;
11725 # endif
11726 # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */
11727 # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
11728 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
11729 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
11730 #endif
11731 
11732 /*
11733 ** Constants for the largest and smallest possible 64-bit signed integers.
11734 ** These macros are designed to work correctly on both 32-bit and 64-bit
11735 ** compilers.
11736 */
11737 #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
11738 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
11739 
11740 /*
11741 ** Round up a number to the next larger multiple of 8. This is used
11742 ** to force 8-byte alignment on 64-bit architectures.
11743 */
11744 #define ROUND8(x) (((x)+7)&~7)
11745 
11746 /*
11747 ** Round down to the nearest multiple of 8
11748 */
11749 #define ROUNDDOWN8(x) ((x)&~7)
11750 
11751 /*
11752 ** Assert that the pointer X is aligned to an 8-byte boundary. This
11753 ** macro is used only within assert() to verify that the code gets
11754 ** all alignment restrictions correct.
11755 **
11756 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
11757 ** underlying malloc() implementation might return us 4-byte aligned
11758 ** pointers. In that case, only verify 4-byte alignment.
11759 */
11760 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
11761 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
11762 #else
11763 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
11764 #endif
11765 
11766 /*
11767 ** Disable MMAP on platforms where it is known to not work
11768 */
11769 #if defined(__OpenBSD__) || defined(__QNXNTO__)
11770 # undef SQLITE_MAX_MMAP_SIZE
11771 # define SQLITE_MAX_MMAP_SIZE 0
11772 #endif
11773 
11774 /*
11775 ** Default maximum size of memory used by memory-mapped I/O in the VFS
11776 */
11777 #ifdef __APPLE__
11778 # include <TargetConditionals.h>
11779 #endif
11780 #ifndef SQLITE_MAX_MMAP_SIZE
11781 # if defined(__linux__) \
11782  || defined(_WIN32) \
11783  || (defined(__APPLE__) && defined(__MACH__)) \
11784  || defined(__sun) \
11785  || defined(__FreeBSD__) \
11786  || defined(__DragonFly__)
11787 # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
11788 # else
11789 # define SQLITE_MAX_MMAP_SIZE 0
11790 # endif
11791 # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
11792 #endif
11793 
11794 /*
11795 ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
11796 ** default MMAP_SIZE is specified at compile-time, make sure that it does
11797 ** not exceed the maximum mmap size.
11798 */
11799 #ifndef SQLITE_DEFAULT_MMAP_SIZE
11800 # define SQLITE_DEFAULT_MMAP_SIZE 0
11801 # define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */
11802 #endif
11803 #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
11804 # undef SQLITE_DEFAULT_MMAP_SIZE
11805 # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
11806 #endif
11807 
11808 /*
11809 ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
11810 ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
11811 ** define SQLITE_ENABLE_STAT3_OR_STAT4
11812 */
11813 #ifdef SQLITE_ENABLE_STAT4
11814 # undef SQLITE_ENABLE_STAT3
11815 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
11816 #elif SQLITE_ENABLE_STAT3
11817 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
11818 #elif SQLITE_ENABLE_STAT3_OR_STAT4
11819 # undef SQLITE_ENABLE_STAT3_OR_STAT4
11820 #endif
11821 
11822 /*
11823 ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
11824 ** the Select query generator tracing logic is turned on.
11825 */
11826 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE)
11827 # define SELECTTRACE_ENABLED 1
11828 #else
11829 # define SELECTTRACE_ENABLED 0
11830 #endif
11831 
11832 /*
11833 ** An instance of the following structure is used to store the busy-handler
11834 ** callback for a given sqlite handle.
11835 **
11836 ** The sqlite.busyHandler member of the sqlite struct contains the busy
11837 ** callback for the database handle. Each pager opened via the sqlite
11838 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
11839 ** callback is currently invoked only from within pager.c.
11840 */
11841 typedef struct BusyHandler BusyHandler;
11842 struct BusyHandler {
11843  int (*xFunc)(void *,int); /* The busy callback */
11844  void *pArg; /* First arg to busy callback */
11845  int nBusy; /* Incremented with each busy call */
11846 };
11847 
11848 /*
11849 ** Name of the master database table. The master database table
11850 ** is a special table that holds the names and attributes of all
11851 ** user tables and indices.
11852 */
11853 #define MASTER_NAME "sqlite_master"
11854 #define TEMP_MASTER_NAME "sqlite_temp_master"
11855 
11856 /*
11857 ** The root-page of the master database table.
11858 */
11859 #define MASTER_ROOT 1
11860 
11861 /*
11862 ** The name of the schema table.
11863 */
11864 #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
11865 
11866 /*
11867 ** A convenience macro that returns the number of elements in
11868 ** an array.
11869 */
11870 #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
11871 
11872 /*
11873 ** Determine if the argument is a power of two
11874 */
11875 #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
11876 
11877 /*
11878 ** The following value as a destructor means to use sqlite3DbFree().
11879 ** The sqlite3DbFree() routine requires two parameters instead of the
11880 ** one parameter that destructors normally want. So we have to introduce
11881 ** this magic value that the code knows to handle differently. Any
11882 ** pointer will work here as long as it is distinct from SQLITE_STATIC
11883 ** and SQLITE_TRANSIENT.
11884 */
11885 #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
11886 
11887 /*
11888 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
11889 ** not support Writable Static Data (WSD) such as global and static variables.
11890 ** All variables must either be on the stack or dynamically allocated from
11891 ** the heap. When WSD is unsupported, the variable declarations scattered
11892 ** throughout the SQLite code must become constants instead. The SQLITE_WSD
11893 ** macro is used for this purpose. And instead of referencing the variable
11894 ** directly, we use its constant as a key to lookup the run-time allocated
11895 ** buffer that holds real variable. The constant is also the initializer
11896 ** for the run-time allocated buffer.
11897 **
11898 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
11899 ** macros become no-ops and have zero performance impact.
11900 */
11901 #ifdef SQLITE_OMIT_WSD
11902  #define SQLITE_WSD const
11903  #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
11904  #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
11905 SQLITE_API int SQLITE_STDCALL sqlite3_wsd_init(int N, int J);
11906 SQLITE_API void *SQLITE_STDCALL sqlite3_wsd_find(void *K, int L);
11907 #else
11908  #define SQLITE_WSD
11909  #define GLOBAL(t,v) v
11910  #define sqlite3GlobalConfig sqlite3Config
11911 #endif
11912 
11913 /*
11914 ** The following macros are used to suppress compiler warnings and to
11915 ** make it clear to human readers when a function parameter is deliberately
11916 ** left unused within the body of a function. This usually happens when
11917 ** a function is called via a function pointer. For example the
11918 ** implementation of an SQL aggregate step callback may not use the
11919 ** parameter indicating the number of arguments passed to the aggregate,
11920 ** if it knows that this is enforced elsewhere.
11921 **
11922 ** When a function parameter is not used at all within the body of a function,
11923 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
11924 ** However, these macros may also be used to suppress warnings related to
11925 ** parameters that may or may not be used depending on compilation options.
11926 ** For example those parameters only used in assert() statements. In these
11927 ** cases the parameters are named as per the usual conventions.
11928 */
11929 #define UNUSED_PARAMETER(x) (void)(x)
11930 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
11931 
11932 /*
11933 ** Forward references to structures
11934 */
11935 typedef struct AggInfo AggInfo;
11936 typedef struct AuthContext AuthContext;
11937 typedef struct AutoincInfo AutoincInfo;
11938 typedef struct Bitvec Bitvec;
11939 typedef struct CollSeq CollSeq;
11940 typedef struct Column Column;
11941 typedef struct Db Db;
11942 typedef struct Schema Schema;
11943 typedef struct Expr Expr;
11944 typedef struct ExprList ExprList;
11945 typedef struct ExprSpan ExprSpan;
11946 typedef struct FKey FKey;
11947 typedef struct FuncDestructor FuncDestructor;
11948 typedef struct FuncDef FuncDef;
11949 typedef struct FuncDefHash FuncDefHash;
11950 typedef struct IdList IdList;
11951 typedef struct Index Index;
11952 typedef struct IndexSample IndexSample;
11953 typedef struct KeyClass KeyClass;
11954 typedef struct KeyInfo KeyInfo;
11955 typedef struct Lookaside Lookaside;
11956 typedef struct LookasideSlot LookasideSlot;
11957 typedef struct Module Module;
11958 typedef struct NameContext NameContext;
11959 typedef struct Parse Parse;
11960 typedef struct PreUpdate PreUpdate;
11961 typedef struct PrintfArguments PrintfArguments;
11962 typedef struct RowSet RowSet;
11963 typedef struct Savepoint Savepoint;
11964 typedef struct Select Select;
11965 typedef struct SQLiteThread SQLiteThread;
11966 typedef struct SelectDest SelectDest;
11967 typedef struct SrcList SrcList;
11968 typedef struct StrAccum StrAccum;
11969 typedef struct Table Table;
11970 typedef struct TableLock TableLock;
11971 typedef struct Token Token;
11972 typedef struct TreeView TreeView;
11973 typedef struct Trigger Trigger;
11974 typedef struct TriggerPrg TriggerPrg;
11975 typedef struct TriggerStep TriggerStep;
11976 typedef struct UnpackedRecord UnpackedRecord;
11977 typedef struct VTable VTable;
11978 typedef struct VtabCtx VtabCtx;
11979 typedef struct Walker Walker;
11980 typedef struct WhereInfo WhereInfo;
11981 typedef struct With With;
11982 
11983 /*
11984 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
11985 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
11986 ** pointer types (i.e. FuncDef) defined above.
11987 */
11988 /************** Include btree.h in the middle of sqliteInt.h *****************/
11989 /************** Begin file btree.h *******************************************/
11990 /*
11991 ** 2001 September 15
11992 **
11993 ** The author disclaims copyright to this source code. In place of
11994 ** a legal notice, here is a blessing:
11995 **
11996 ** May you do good and not evil.
11997 ** May you find forgiveness for yourself and forgive others.
11998 ** May you share freely, never taking more than you give.
11999 **
12000 *************************************************************************
12001 ** This header file defines the interface that the sqlite B-Tree file
12002 ** subsystem. See comments in the source code for a detailed description
12003 ** of what each interface routine does.
12004 */
12005 #ifndef SQLITE_BTREE_H
12006 #define SQLITE_BTREE_H
12007 
12008 /* TODO: This definition is just included so other modules compile. It
12009 ** needs to be revisited.
12010 */
12011 #define SQLITE_N_BTREE_META 16
12012 
12013 /*
12014 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
12015 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
12016 */
12017 #ifndef SQLITE_DEFAULT_AUTOVACUUM
12018  #define SQLITE_DEFAULT_AUTOVACUUM 0
12019 #endif
12020 
12021 #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
12022 #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
12023 #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
12024 
12025 /*
12026 ** Forward declarations of structure
12027 */
12028 typedef struct Btree Btree;
12029 typedef struct BtCursor BtCursor;
12030 typedef struct BtShared BtShared;
12031 typedef struct BtreePayload BtreePayload;
12032 
12033 
12034 SQLITE_PRIVATE int sqlite3BtreeOpen(
12035  sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
12036  const char *zFilename, /* Name of database file to open */
12037  sqlite3 *db, /* Associated database connection */
12038  Btree **ppBtree, /* Return open Btree* here */
12039  int flags, /* Flags */
12040  int vfsFlags /* Flags passed through to VFS open */
12041 );
12042 
12043 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
12044 ** following values.
12045 **
12046 ** NOTE: These values must match the corresponding PAGER_ values in
12047 ** pager.h.
12048 */
12049 #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
12050 #define BTREE_MEMORY 2 /* This is an in-memory DB */
12051 #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
12052 #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
12053 
12054 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
12055 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
12056 SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
12057 #if SQLITE_MAX_MMAP_SIZE>0
12058 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
12059 #endif
12060 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
12061 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
12062 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
12063 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
12064 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
12065 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
12066 SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
12067 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
12068 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
12069 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
12070 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
12071 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
12072 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
12073 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
12074 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
12075 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
12076 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
12077 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
12078 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
12079 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
12080 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
12081 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
12082 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
12083 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
12084 
12085 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
12086 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
12087 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
12088 
12089 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
12090 
12091 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
12092 ** of the flags shown below.
12093 **
12094 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
12095 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
12096 ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
12097 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
12098 ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
12099 ** indices.)
12100 */
12101 #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
12102 #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
12103 
12104 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
12105 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
12106 SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
12107 SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
12108 
12109 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
12110 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
12111 
12112 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
12113 
12114 /*
12115 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
12116 ** should be one of the following values. The integer values are assigned
12117 ** to constants so that the offset of the corresponding field in an
12118 ** SQLite database header may be found using the following formula:
12119 **
12120 ** offset = 36 + (idx * 4)
12121 **
12122 ** For example, the free-page-count field is located at byte offset 36 of
12123 ** the database file header. The incr-vacuum-flag field is located at
12124 ** byte offset 64 (== 36+4*7).
12125 **
12126 ** The BTREE_DATA_VERSION value is not really a value stored in the header.
12127 ** It is a read-only number computed by the pager. But we merge it with
12128 ** the header value access routines since its access pattern is the same.
12129 ** Call it a "virtual meta value".
12130 */
12131 #define BTREE_FREE_PAGE_COUNT 0
12132 #define BTREE_SCHEMA_VERSION 1
12133 #define BTREE_FILE_FORMAT 2
12134 #define BTREE_DEFAULT_CACHE_SIZE 3
12135 #define BTREE_LARGEST_ROOT_PAGE 4
12136 #define BTREE_TEXT_ENCODING 5
12137 #define BTREE_USER_VERSION 6
12138 #define BTREE_INCR_VACUUM 7
12139 #define BTREE_APPLICATION_ID 8
12140 #define BTREE_DATA_VERSION 15 /* A virtual meta-value */
12141 
12142 /*
12143 ** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
12144 ** interface.
12145 **
12146 ** BTREE_HINT_RANGE (arguments: Expr*, Mem*)
12147 **
12148 ** The first argument is an Expr* (which is guaranteed to be constant for
12149 ** the lifetime of the cursor) that defines constraints on which rows
12150 ** might be fetched with this cursor. The Expr* tree may contain
12151 ** TK_REGISTER nodes that refer to values stored in the array of registers
12152 ** passed as the second parameter. In other words, if Expr.op==TK_REGISTER
12153 ** then the value of the node is the value in Mem[pExpr.iTable]. Any
12154 ** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
12155 ** column of the b-tree of the cursor. The Expr tree will not contain
12156 ** any function calls nor subqueries nor references to b-trees other than
12157 ** the cursor being hinted.
12158 **
12159 ** The design of the _RANGE hint is aid b-tree implementations that try
12160 ** to prefetch content from remote machines - to provide those
12161 ** implementations with limits on what needs to be prefetched and thereby
12162 ** reduce network bandwidth.
12163 **
12164 ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
12165 ** standard SQLite. The other hints are provided for extentions that use
12166 ** the SQLite parser and code generator but substitute their own storage
12167 ** engine.
12168 */
12169 #define BTREE_HINT_RANGE 0 /* Range constraints on queries */
12170 
12171 /*
12172 ** Values that may be OR'd together to form the argument to the
12173 ** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
12174 **
12175 ** The BTREE_BULKLOAD flag is set on index cursors when the index is going
12176 ** to be filled with content that is already in sorted order.
12177 **
12178 ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
12179 ** OP_SeekLE opcodes for a range search, but where the range of entries
12180 ** selected will all have the same key. In other words, the cursor will
12181 ** be used only for equality key searches.
12182 **
12183 */
12184 #define BTREE_BULKLOAD 0x00000001 /* Used to full index in sorted order */
12185 #define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */
12186 
12187 /*
12188 ** Flags passed as the third argument to sqlite3BtreeCursor().
12189 **
12190 ** For read-only cursors the wrFlag argument is always zero. For read-write
12191 ** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
12192 ** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
12193 ** only be used by SQLite for the following:
12194 **
12195 ** * to seek to and then delete specific entries, and/or
12196 **
12197 ** * to read values that will be used to create keys that other
12198 ** BTREE_FORDELETE cursors will seek to and delete.
12199 **
12200 ** The BTREE_FORDELETE flag is an optimization hint. It is not used by
12201 ** by this, the native b-tree engine of SQLite, but it is available to
12202 ** alternative storage engines that might be substituted in place of this
12203 ** b-tree system. For alternative storage engines in which a delete of
12204 ** the main table row automatically deletes corresponding index rows,
12205 ** the FORDELETE flag hint allows those alternative storage engines to
12206 ** skip a lot of work. Namely: FORDELETE cursors may treat all SEEK
12207 ** and DELETE operations as no-ops, and any READ operation against a
12208 ** FORDELETE cursor may return a null row: 0x01 0x00.
12209 */
12210 #define BTREE_WRCSR 0x00000004 /* read-write cursor */
12211 #define BTREE_FORDELETE 0x00000008 /* Cursor is for seek/delete only */
12212 
12213 SQLITE_PRIVATE int sqlite3BtreeCursor(
12214  Btree*, /* BTree containing table to open */
12215  int iTable, /* Index of root page */
12216  int wrFlag, /* 1 for writing. 0 for read-only */
12217  struct KeyInfo*, /* First argument to compare function */
12218  BtCursor *pCursor /* Space to write cursor structure */
12219 );
12220 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
12221 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
12222 SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
12223 #ifdef SQLITE_ENABLE_CURSOR_HINTS
12224 SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
12225 #endif
12226 
12227 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
12228 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
12229  BtCursor*,
12230  UnpackedRecord *pUnKey,
12231  i64 intKey,
12232  int bias,
12233  int *pRes
12234 );
12235 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
12236 SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
12237 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
12238 
12239 /* Allowed flags for the 2nd argument to sqlite3BtreeDelete() */
12240 #define BTREE_SAVEPOSITION 0x02 /* Leave cursor pointing at NEXT or PREV */
12241 #define BTREE_AUXDELETE 0x04 /* not the primary delete operation */
12242 
12243 /* An instance of the BtreePayload object describes the content of a single
12244 ** entry in either an index or table btree.
12245 **
12246 ** Index btrees (used for indexes and also WITHOUT ROWID tables) contain
12247 ** an arbitrary key and no data. These btrees have pKey,nKey set to their
12248 ** key and pData,nData,nZero set to zero.
12249 **
12250 ** Table btrees (used for rowid tables) contain an integer rowid used as
12251 ** the key and passed in the nKey field. The pKey field is zero.
12252 ** pData,nData hold the content of the new entry. nZero extra zero bytes
12253 ** are appended to the end of the content when constructing the entry.
12254 **
12255 ** This object is used to pass information into sqlite3BtreeInsert(). The
12256 ** same information used to be passed as five separate parameters. But placing
12257 ** the information into this object helps to keep the interface more
12258 ** organized and understandable, and it also helps the resulting code to
12259 ** run a little faster by using fewer registers for parameter passing.
12260 */
12261 struct BtreePayload {
12262  const void *pKey; /* Key content for indexes. NULL for tables */
12263  sqlite3_int64 nKey; /* Size of pKey for indexes. PRIMARY KEY for tabs */
12264  const void *pData; /* Data for tables. NULL for indexes */
12265  int nData; /* Size of pData. 0 if none. */
12266  int nZero; /* Extra zero data appended after pData,nData */
12267 };
12268 
12269 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,
12270  int bias, int seekResult);
12271 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
12272 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
12273 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
12274 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
12275 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
12276 SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*);
12277 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
12278 SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);
12279 SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*);
12280 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
12281 
12282 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
12283 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
12284 
12285 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
12286 SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
12287 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
12288 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
12289 SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
12290 SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
12291 SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
12292 
12293 #ifndef NDEBUG
12294 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
12295 #endif
12296 
12297 #ifndef SQLITE_OMIT_BTREECOUNT
12298 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
12299 #endif
12300 
12301 #ifdef SQLITE_TEST
12302 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
12303 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
12304 #endif
12305 
12306 #ifndef SQLITE_OMIT_WAL
12307 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
12308 #endif
12309 
12310 /*
12311 ** If we are not using shared cache, then there is no need to
12312 ** use mutexes to access the BtShared structures. So make the
12313 ** Enter and Leave procedures no-ops.
12314 */
12315 #ifndef SQLITE_OMIT_SHARED_CACHE
12316 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
12317 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
12318 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
12319 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
12320 SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree*);
12321 #else
12322 # define sqlite3BtreeEnter(X)
12323 # define sqlite3BtreeEnterAll(X)
12324 # define sqlite3BtreeSharable(X) 0
12325 # define sqlite3BtreeEnterCursor(X)
12326 # define sqlite3BtreeConnectionCount(X) 1
12327 #endif
12328 
12329 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
12330 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
12331 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
12332 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
12333 #ifndef NDEBUG
12334  /* These routines are used inside assert() statements only. */
12335 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
12336 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
12337 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
12338 #endif
12339 #else
12340 
12341 # define sqlite3BtreeLeave(X)
12342 # define sqlite3BtreeLeaveCursor(X)
12343 # define sqlite3BtreeLeaveAll(X)
12344 
12345 # define sqlite3BtreeHoldsMutex(X) 1
12346 # define sqlite3BtreeHoldsAllMutexes(X) 1
12347 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
12348 #endif
12349 
12350 
12351 #endif /* SQLITE_BTREE_H */
12352 
12353 /************** End of btree.h ***********************************************/
12354 /************** Continuing where we left off in sqliteInt.h ******************/
12355 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
12356 /************** Begin file vdbe.h ********************************************/
12357 /*
12358 ** 2001 September 15
12359 **
12360 ** The author disclaims copyright to this source code. In place of
12361 ** a legal notice, here is a blessing:
12362 **
12363 ** May you do good and not evil.
12364 ** May you find forgiveness for yourself and forgive others.
12365 ** May you share freely, never taking more than you give.
12366 **
12367 *************************************************************************
12368 ** Header file for the Virtual DataBase Engine (VDBE)
12369 **
12370 ** This header defines the interface to the virtual database engine
12371 ** or VDBE. The VDBE implements an abstract machine that runs a
12372 ** simple program to access and modify the underlying database.
12373 */
12374 #ifndef SQLITE_VDBE_H
12375 #define SQLITE_VDBE_H
12376 /* #include <stdio.h> */
12377 
12378 /*
12379 ** A single VDBE is an opaque structure named "Vdbe". Only routines
12380 ** in the source file sqliteVdbe.c are allowed to see the insides
12381 ** of this structure.
12382 */
12383 typedef struct Vdbe Vdbe;
12384 
12385 /*
12386 ** The names of the following types declared in vdbeInt.h are required
12387 ** for the VdbeOp definition.
12388 */
12389 typedef struct Mem Mem;
12390 typedef struct SubProgram SubProgram;
12391 
12392 /*
12393 ** A single instruction of the virtual machine has an opcode
12394 ** and as many as three operands. The instruction is recorded
12395 ** as an instance of the following structure:
12396 */
12397 struct VdbeOp {
12398  u8 opcode; /* What operation to perform */
12399  signed char p4type; /* One of the P4_xxx constants for p4 */
12400  u8 notUsed1;
12401  u8 p5; /* Fifth parameter is an unsigned character */
12402  int p1; /* First operand */
12403  int p2; /* Second parameter (often the jump destination) */
12404  int p3; /* The third parameter */
12405  union p4union { /* fourth parameter */
12406  int i; /* Integer value if p4type==P4_INT32 */
12407  void *p; /* Generic pointer */
12408  char *z; /* Pointer to data for string (char array) types */
12409  i64 *pI64; /* Used when p4type is P4_INT64 */
12410  double *pReal; /* Used when p4type is P4_REAL */
12411  FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
12412  sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
12413  CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
12414  Mem *pMem; /* Used when p4type is P4_MEM */
12415  VTable *pVtab; /* Used when p4type is P4_VTAB */
12416  KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
12417  int *ai; /* Used when p4type is P4_INTARRAY */
12418  SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
12419  Table *pTab; /* Used when p4type is P4_TABLE */
12420 #ifdef SQLITE_ENABLE_CURSOR_HINTS
12421  Expr *pExpr; /* Used when p4type is P4_EXPR */
12422 #endif
12423  int (*xAdvance)(BtCursor *, int *);
12424  } p4;
12425 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
12426  char *zComment; /* Comment to improve readability */
12427 #endif
12428 #ifdef VDBE_PROFILE
12429  u32 cnt; /* Number of times this instruction was executed */
12430  u64 cycles; /* Total time spent executing this instruction */
12431 #endif
12432 #ifdef SQLITE_VDBE_COVERAGE
12433  int iSrcLine; /* Source-code line that generated this opcode */
12434 #endif
12435 };
12436 typedef struct VdbeOp VdbeOp;
12437 
12438 
12439 /*
12440 ** A sub-routine used to implement a trigger program.
12441 */
12442 struct SubProgram {
12443  VdbeOp *aOp; /* Array of opcodes for sub-program */
12444  int nOp; /* Elements in aOp[] */
12445  int nMem; /* Number of memory cells required */
12446  int nCsr; /* Number of cursors required */
12447  int nOnce; /* Number of OP_Once instructions */
12448  void *token; /* id that may be used to recursive triggers */
12449  SubProgram *pNext; /* Next sub-program already visited */
12450 };
12451 
12452 /*
12453 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
12454 ** it takes up less space.
12455 */
12456 struct VdbeOpList {
12457  u8 opcode; /* What operation to perform */
12458  signed char p1; /* First operand */
12459  signed char p2; /* Second parameter (often the jump destination) */
12460  signed char p3; /* Third parameter */
12461 };
12462 typedef struct VdbeOpList VdbeOpList;
12463 
12464 /*
12465 ** Allowed values of VdbeOp.p4type
12466 */
12467 #define P4_NOTUSED 0 /* The P4 parameter is not used */
12468 #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
12469 #define P4_STATIC (-2) /* Pointer to a static string */
12470 #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
12471 #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
12472 #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
12473 #define P4_EXPR (-7) /* P4 is a pointer to an Expr tree */
12474 #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
12475 #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
12476 #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
12477 #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
12478 #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
12479 #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
12480 #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
12481 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
12482 #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
12483 #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
12484 #define P4_TABLE (-20) /* P4 is a pointer to a Table structure */
12485 #define P4_FUNCCTX (-21) /* P4 is a pointer to an sqlite3_context object */
12486 
12487 /* Error message codes for OP_Halt */
12488 #define P5_ConstraintNotNull 1
12489 #define P5_ConstraintUnique 2
12490 #define P5_ConstraintCheck 3
12491 #define P5_ConstraintFK 4
12492 
12493 /*
12494 ** The Vdbe.aColName array contains 5n Mem structures, where n is the
12495 ** number of columns of data returned by the statement.
12496 */
12497 #define COLNAME_NAME 0
12498 #define COLNAME_DECLTYPE 1
12499 #define COLNAME_DATABASE 2
12500 #define COLNAME_TABLE 3
12501 #define COLNAME_COLUMN 4
12502 #ifdef SQLITE_ENABLE_COLUMN_METADATA
12503 # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
12504 #else
12505 # ifdef SQLITE_OMIT_DECLTYPE
12506 # define COLNAME_N 1 /* Store only the name */
12507 # else
12508 # define COLNAME_N 2 /* Store the name and decltype */
12509 # endif
12510 #endif
12511 
12512 /*
12513 ** The following macro converts a relative address in the p2 field
12514 ** of a VdbeOp structure into a negative number so that
12515 ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
12516 ** the macro again restores the address.
12517 */
12518 #define ADDR(X) (-1-(X))
12519 
12520 /*
12521 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
12522 ** header file that defines a number for each opcode used by the VDBE.
12523 */
12524 /************** Include opcodes.h in the middle of vdbe.h ********************/
12525 /************** Begin file opcodes.h *****************************************/
12526 /* Automatically generated. Do not edit */
12527 /* See the tool/mkopcodeh.tcl script for details */
12528 #define OP_Savepoint 0
12529 #define OP_AutoCommit 1
12530 #define OP_Transaction 2
12531 #define OP_SorterNext 3
12532 #define OP_PrevIfOpen 4
12533 #define OP_NextIfOpen 5
12534 #define OP_Prev 6
12535 #define OP_Next 7
12536 #define OP_Checkpoint 8
12537 #define OP_JournalMode 9
12538 #define OP_Vacuum 10
12539 #define OP_VFilter 11 /* synopsis: iplan=r[P3] zplan='P4' */
12540 #define OP_VUpdate 12 /* synopsis: data=r[P3@P2] */
12541 #define OP_Goto 13
12542 #define OP_Gosub 14
12543 #define OP_InitCoroutine 15
12544 #define OP_Yield 16
12545 #define OP_MustBeInt 17
12546 #define OP_Jump 18
12547 #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
12548 #define OP_Once 20
12549 #define OP_If 21
12550 #define OP_IfNot 22
12551 #define OP_SeekLT 23 /* synopsis: key=r[P3@P4] */
12552 #define OP_SeekLE 24 /* synopsis: key=r[P3@P4] */
12553 #define OP_SeekGE 25 /* synopsis: key=r[P3@P4] */
12554 #define OP_SeekGT 26 /* synopsis: key=r[P3@P4] */
12555 #define OP_Or 27 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
12556 #define OP_And 28 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
12557 #define OP_NoConflict 29 /* synopsis: key=r[P3@P4] */
12558 #define OP_NotFound 30 /* synopsis: key=r[P3@P4] */
12559 #define OP_Found 31 /* synopsis: key=r[P3@P4] */
12560 #define OP_SeekRowid 32 /* synopsis: intkey=r[P3] */
12561 #define OP_NotExists 33 /* synopsis: intkey=r[P3] */
12562 #define OP_IsNull 34 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
12563 #define OP_NotNull 35 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
12564 #define OP_Ne 36 /* same as TK_NE, synopsis: if r[P1]!=r[P3] goto P2 */
12565 #define OP_Eq 37 /* same as TK_EQ, synopsis: if r[P1]==r[P3] goto P2 */
12566 #define OP_Gt 38 /* same as TK_GT, synopsis: if r[P1]>r[P3] goto P2 */
12567 #define OP_Le 39 /* same as TK_LE, synopsis: if r[P1]<=r[P3] goto P2 */
12568 #define OP_Lt 40 /* same as TK_LT, synopsis: if r[P1]<r[P3] goto P2 */
12569 #define OP_Ge 41 /* same as TK_GE, synopsis: if r[P1]>=r[P3] goto P2 */
12570 #define OP_Last 42
12571 #define OP_BitAnd 43 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
12572 #define OP_BitOr 44 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
12573 #define OP_ShiftLeft 45 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
12574 #define OP_ShiftRight 46 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
12575 #define OP_Add 47 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
12576 #define OP_Subtract 48 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
12577 #define OP_Multiply 49 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
12578 #define OP_Divide 50 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
12579 #define OP_Remainder 51 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
12580 #define OP_Concat 52 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
12581 #define OP_SorterSort 53
12582 #define OP_BitNot 54 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
12583 #define OP_Sort 55
12584 #define OP_Rewind 56
12585 #define OP_IdxLE 57 /* synopsis: key=r[P3@P4] */
12586 #define OP_IdxGT 58 /* synopsis: key=r[P3@P4] */
12587 #define OP_IdxLT 59 /* synopsis: key=r[P3@P4] */
12588 #define OP_IdxGE 60 /* synopsis: key=r[P3@P4] */
12589 #define OP_RowSetRead 61 /* synopsis: r[P3]=rowset(P1) */
12590 #define OP_RowSetTest 62 /* synopsis: if r[P3] in rowset(P1) goto P2 */
12591 #define OP_Program 63
12592 #define OP_FkIfZero 64 /* synopsis: if fkctr[P1]==0 goto P2 */
12593 #define OP_IfPos 65 /* synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
12594 #define OP_IfNotZero 66 /* synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2 */
12595 #define OP_DecrJumpZero 67 /* synopsis: if (--r[P1])==0 goto P2 */
12596 #define OP_IncrVacuum 68
12597 #define OP_VNext 69
12598 #define OP_Init 70 /* synopsis: Start at P2 */
12599 #define OP_Return 71
12600 #define OP_EndCoroutine 72
12601 #define OP_HaltIfNull 73 /* synopsis: if r[P3]=null halt */
12602 #define OP_Halt 74
12603 #define OP_Integer 75 /* synopsis: r[P2]=P1 */
12604 #define OP_Int64 76 /* synopsis: r[P2]=P4 */
12605 #define OP_String 77 /* synopsis: r[P2]='P4' (len=P1) */
12606 #define OP_Null 78 /* synopsis: r[P2..P3]=NULL */
12607 #define OP_SoftNull 79 /* synopsis: r[P1]=NULL */
12608 #define OP_Blob 80 /* synopsis: r[P2]=P4 (len=P1) */
12609 #define OP_Variable 81 /* synopsis: r[P2]=parameter(P1,P4) */
12610 #define OP_Move 82 /* synopsis: r[P2@P3]=r[P1@P3] */
12611 #define OP_Copy 83 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
12612 #define OP_SCopy 84 /* synopsis: r[P2]=r[P1] */
12613 #define OP_IntCopy 85 /* synopsis: r[P2]=r[P1] */
12614 #define OP_ResultRow 86 /* synopsis: output=r[P1@P2] */
12615 #define OP_CollSeq 87
12616 #define OP_Function0 88 /* synopsis: r[P3]=func(r[P2@P5]) */
12617 #define OP_Function 89 /* synopsis: r[P3]=func(r[P2@P5]) */
12618 #define OP_AddImm 90 /* synopsis: r[P1]=r[P1]+P2 */
12619 #define OP_RealAffinity 91
12620 #define OP_Cast 92 /* synopsis: affinity(r[P1]) */
12621 #define OP_Permutation 93
12622 #define OP_Compare 94 /* synopsis: r[P1@P3] <-> r[P2@P3] */
12623 #define OP_Column 95 /* synopsis: r[P3]=PX */
12624 #define OP_Affinity 96 /* synopsis: affinity(r[P1@P2]) */
12625 #define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */
12626 #define OP_MakeRecord 98 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
12627 #define OP_Count 99 /* synopsis: r[P2]=count() */
12628 #define OP_ReadCookie 100
12629 #define OP_SetCookie 101
12630 #define OP_ReopenIdx 102 /* synopsis: root=P2 iDb=P3 */
12631 #define OP_OpenRead 103 /* synopsis: root=P2 iDb=P3 */
12632 #define OP_OpenWrite 104 /* synopsis: root=P2 iDb=P3 */
12633 #define OP_OpenAutoindex 105 /* synopsis: nColumn=P2 */
12634 #define OP_OpenEphemeral 106 /* synopsis: nColumn=P2 */
12635 #define OP_SorterOpen 107
12636 #define OP_SequenceTest 108 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
12637 #define OP_OpenPseudo 109 /* synopsis: P3 columns in r[P2] */
12638 #define OP_Close 110
12639 #define OP_ColumnsUsed 111
12640 #define OP_Sequence 112 /* synopsis: r[P2]=cursor[P1].ctr++ */
12641 #define OP_NewRowid 113 /* synopsis: r[P2]=rowid */
12642 #define OP_Insert 114 /* synopsis: intkey=r[P3] data=r[P2] */
12643 #define OP_InsertInt 115 /* synopsis: intkey=P3 data=r[P2] */
12644 #define OP_Delete 116
12645 #define OP_ResetCount 117
12646 #define OP_SorterCompare 118 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
12647 #define OP_SorterData 119 /* synopsis: r[P2]=data */
12648 #define OP_RowKey 120 /* synopsis: r[P2]=key */
12649 #define OP_RowData 121 /* synopsis: r[P2]=data */
12650 #define OP_Rowid 122 /* synopsis: r[P2]=rowid */
12651 #define OP_NullRow 123
12652 #define OP_SorterInsert 124
12653 #define OP_IdxInsert 125 /* synopsis: key=r[P2] */
12654 #define OP_IdxDelete 126 /* synopsis: key=r[P2@P3] */
12655 #define OP_Seek 127 /* synopsis: Move P3 to P1.rowid */
12656 #define OP_IdxRowid 128 /* synopsis: r[P2]=rowid */
12657 #define OP_Destroy 129
12658 #define OP_Clear 130
12659 #define OP_ResetSorter 131
12660 #define OP_CreateIndex 132 /* synopsis: r[P2]=root iDb=P1 */
12661 #define OP_Real 133 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
12662 #define OP_CreateTable 134 /* synopsis: r[P2]=root iDb=P1 */
12663 #define OP_ParseSchema 135
12664 #define OP_LoadAnalysis 136
12665 #define OP_DropTable 137
12666 #define OP_DropIndex 138
12667 #define OP_DropTrigger 139
12668 #define OP_IntegrityCk 140
12669 #define OP_RowSetAdd 141 /* synopsis: rowset(P1)=r[P2] */
12670 #define OP_Param 142
12671 #define OP_FkCounter 143 /* synopsis: fkctr[P1]+=P2 */
12672 #define OP_MemMax 144 /* synopsis: r[P1]=max(r[P1],r[P2]) */
12673 #define OP_OffsetLimit 145 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
12674 #define OP_AggStep0 146 /* synopsis: accum=r[P3] step(r[P2@P5]) */
12675 #define OP_AggStep 147 /* synopsis: accum=r[P3] step(r[P2@P5]) */
12676 #define OP_AggFinal 148 /* synopsis: accum=r[P1] N=P2 */
12677 #define OP_Expire 149
12678 #define OP_TableLock 150 /* synopsis: iDb=P1 root=P2 write=P3 */
12679 #define OP_VBegin 151
12680 #define OP_VCreate 152
12681 #define OP_VDestroy 153
12682 #define OP_VOpen 154
12683 #define OP_VColumn 155 /* synopsis: r[P3]=vcolumn(P2) */
12684 #define OP_VRename 156
12685 #define OP_Pagecount 157
12686 #define OP_MaxPgcnt 158
12687 #define OP_CursorHint 159
12688 #define OP_Noop 160
12689 #define OP_Explain 161
12690 
12691 /* Properties such as "out2" or "jump" that are specified in
12692 ** comments following the "case" for each opcode in the vdbe.c
12693 ** are encoded into bitvectors as follows:
12694 */
12695 #define OPFLG_JUMP 0x01 /* jump: P2 holds jmp target */
12696 #define OPFLG_IN1 0x02 /* in1: P1 is an input */
12697 #define OPFLG_IN2 0x04 /* in2: P2 is an input */
12698 #define OPFLG_IN3 0x08 /* in3: P3 is an input */
12699 #define OPFLG_OUT2 0x10 /* out2: P2 is an output */
12700 #define OPFLG_OUT3 0x20 /* out3: P3 is an output */
12701 #define OPFLG_INITIALIZER {\
12702 /* 0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01,\
12703 /* 8 */ 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01,\
12704 /* 16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0x03, 0x03, 0x09,\
12705 /* 24 */ 0x09, 0x09, 0x09, 0x26, 0x26, 0x09, 0x09, 0x09,\
12706 /* 32 */ 0x09, 0x09, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
12707 /* 40 */ 0x0b, 0x0b, 0x01, 0x26, 0x26, 0x26, 0x26, 0x26,\
12708 /* 48 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x01, 0x12, 0x01,\
12709 /* 56 */ 0x01, 0x01, 0x01, 0x01, 0x01, 0x23, 0x0b, 0x01,\
12710 /* 64 */ 0x01, 0x03, 0x03, 0x03, 0x01, 0x01, 0x01, 0x02,\
12711 /* 72 */ 0x02, 0x08, 0x00, 0x10, 0x10, 0x10, 0x10, 0x00,\
12712 /* 80 */ 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
12713 /* 88 */ 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00, 0x00,\
12714 /* 96 */ 0x00, 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00,\
12715 /* 104 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
12716 /* 112 */ 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
12717 /* 120 */ 0x00, 0x00, 0x10, 0x00, 0x04, 0x04, 0x00, 0x00,\
12718 /* 128 */ 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x10, 0x00,\
12719 /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x10, 0x00,\
12720 /* 144 */ 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
12721 /* 152 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00,\
12722 /* 160 */ 0x00, 0x00,}
12723 
12724 /* The sqlite3P2Values() routine is able to run faster if it knows
12725 ** the value of the largest JUMP opcode. The smaller the maximum
12726 ** JUMP opcode the better, so the mkopcodeh.tcl script that
12727 ** generated this include file strives to group all JUMP opcodes
12728 ** together near the beginning of the list.
12729 */
12730 #define SQLITE_MX_JUMP_OPCODE 70 /* Maximum JUMP opcode */
12731 
12732 /************** End of opcodes.h *********************************************/
12733 /************** Continuing where we left off in vdbe.h ***********************/
12734 
12735 /*
12736 ** Prototypes for the VDBE interface. See comments on the implementation
12737 ** for a description of what each of these routines does.
12738 */
12739 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
12740 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
12741 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
12742 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
12743 SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
12744 SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
12745 SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
12746 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
12747 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
12748 SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
12749 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
12750 SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);
12751 #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
12752 SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
12753 #else
12754 # define sqlite3VdbeVerifyNoMallocRequired(A,B)
12755 #endif
12756 SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
12757 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
12758 SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8);
12759 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
12760 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
12761 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
12762 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
12763 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
12764 SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);
12765 SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
12766 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
12767 SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
12768 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
12769 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
12770 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
12771 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
12772 SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);
12773 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
12774 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
12775 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
12776 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
12777 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
12778 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
12779 #ifdef SQLITE_DEBUG
12780 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
12781 #endif
12782 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
12783 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
12784 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
12785 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
12786 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
12787 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
12788 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
12789 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
12790 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
12791 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
12792 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
12793 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
12794 #ifndef SQLITE_OMIT_TRACE
12795 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
12796 #endif
12797 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
12798 
12799 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
12800 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
12801 SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
12802 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
12803 
12804 typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
12805 SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
12806 
12807 #ifndef SQLITE_OMIT_TRIGGER
12808 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
12809 #endif
12810 
12811 /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
12812 ** each VDBE opcode.
12813 **
12814 ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
12815 ** comments in VDBE programs that show key decision points in the code
12816 ** generator.
12817 */
12818 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
12819 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
12820 # define VdbeComment(X) sqlite3VdbeComment X
12821 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
12822 # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
12823 # ifdef SQLITE_ENABLE_MODULE_COMMENTS
12824 # define VdbeModuleComment(X) sqlite3VdbeNoopComment X
12825 # else
12826 # define VdbeModuleComment(X)
12827 # endif
12828 #else
12829 # define VdbeComment(X)
12830 # define VdbeNoopComment(X)
12831 # define VdbeModuleComment(X)
12832 #endif
12833 
12834 /*
12835 ** The VdbeCoverage macros are used to set a coverage testing point
12836 ** for VDBE branch instructions. The coverage testing points are line
12837 ** numbers in the sqlite3.c source file. VDBE branch coverage testing
12838 ** only works with an amalagmation build. That's ok since a VDBE branch
12839 ** coverage build designed for testing the test suite only. No application
12840 ** should ever ship with VDBE branch coverage measuring turned on.
12841 **
12842 ** VdbeCoverage(v) // Mark the previously coded instruction
12843 ** // as a branch
12844 **
12845 ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
12846 **
12847 ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
12848 **
12849 ** VdbeCoverageNeverTaken(v) // Previous branch is never taken
12850 **
12851 ** Every VDBE branch operation must be tagged with one of the macros above.
12852 ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
12853 ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
12854 ** routine in vdbe.c, alerting the developer to the missed tag.
12855 */
12856 #ifdef SQLITE_VDBE_COVERAGE
12857 SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
12858 # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
12859 # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
12860 # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
12861 # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
12862 # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
12863 #else
12864 # define VdbeCoverage(v)
12865 # define VdbeCoverageIf(v,x)
12866 # define VdbeCoverageAlwaysTaken(v)
12867 # define VdbeCoverageNeverTaken(v)
12868 # define VDBE_OFFSET_LINENO(x) 0
12869 #endif
12870 
12871 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
12872 SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
12873 #else
12874 # define sqlite3VdbeScanStatus(a,b,c,d,e)
12875 #endif
12876 
12877 #endif /* SQLITE_VDBE_H */
12878 
12879 /************** End of vdbe.h ************************************************/
12880 /************** Continuing where we left off in sqliteInt.h ******************/
12881 /************** Include pager.h in the middle of sqliteInt.h *****************/
12882 /************** Begin file pager.h *******************************************/
12883 /*
12884 ** 2001 September 15
12885 **
12886 ** The author disclaims copyright to this source code. In place of
12887 ** a legal notice, here is a blessing:
12888 **
12889 ** May you do good and not evil.
12890 ** May you find forgiveness for yourself and forgive others.
12891 ** May you share freely, never taking more than you give.
12892 **
12893 *************************************************************************
12894 ** This header file defines the interface that the sqlite page cache
12895 ** subsystem. The page cache subsystem reads and writes a file a page
12896 ** at a time and provides a journal for rollback.
12897 */
12898 
12899 #ifndef SQLITE_PAGER_H
12900 #define SQLITE_PAGER_H
12901 
12902 /*
12903 ** Default maximum size for persistent journal files. A negative
12904 ** value means no limit. This value may be overridden using the
12905 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
12906 */
12907 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
12908  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
12909 #endif
12910 
12911 /*
12912 ** The type used to represent a page number. The first page in a file
12913 ** is called page 1. 0 is used to represent "not a page".
12914 */
12915 typedef u32 Pgno;
12916 
12917 /*
12918 ** Each open file is managed by a separate instance of the "Pager" structure.
12919 */
12920 typedef struct Pager Pager;
12921 
12922 /*
12923 ** Handle type for pages.
12924 */
12925 typedef struct PgHdr DbPage;
12926 
12927 /*
12928 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
12929 ** reserved for working around a windows/posix incompatibility). It is
12930 ** used in the journal to signify that the remainder of the journal file
12931 ** is devoted to storing a master journal name - there are no more pages to
12932 ** roll back. See comments for function writeMasterJournal() in pager.c
12933 ** for details.
12934 */
12935 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
12936 
12937 /*
12938 ** Allowed values for the flags parameter to sqlite3PagerOpen().
12939 **
12940 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
12941 */
12942 #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
12943 #define PAGER_MEMORY 0x0002 /* In-memory database */
12944 
12945 /*
12946 ** Valid values for the second argument to sqlite3PagerLockingMode().
12947 */
12948 #define PAGER_LOCKINGMODE_QUERY -1
12949 #define PAGER_LOCKINGMODE_NORMAL 0
12950 #define PAGER_LOCKINGMODE_EXCLUSIVE 1
12951 
12952 /*
12953 ** Numeric constants that encode the journalmode.
12954 **
12955 ** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
12956 ** are exposed in the API via the "PRAGMA journal_mode" command and
12957 ** therefore cannot be changed without a compatibility break.
12958 */
12959 #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
12960 #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
12961 #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
12962 #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
12963 #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
12964 #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
12965 #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
12966 
12967 /*
12968 ** Flags that make up the mask passed to sqlite3PagerGet().
12969 */
12970 #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
12971 #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
12972 
12973 /*
12974 ** Flags for sqlite3PagerSetFlags()
12975 **
12976 ** Value constraints (enforced via assert()):
12977 ** PAGER_FULLFSYNC == SQLITE_FullFSync
12978 ** PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
12979 ** PAGER_CACHE_SPILL == SQLITE_CacheSpill
12980 */
12981 #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
12982 #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
12983 #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
12984 #define PAGER_SYNCHRONOUS_EXTRA 0x04 /* PRAGMA synchronous=EXTRA */
12985 #define PAGER_SYNCHRONOUS_MASK 0x07 /* Mask for four values above */
12986 #define PAGER_FULLFSYNC 0x08 /* PRAGMA fullfsync=ON */
12987 #define PAGER_CKPT_FULLFSYNC 0x10 /* PRAGMA checkpoint_fullfsync=ON */
12988 #define PAGER_CACHESPILL 0x20 /* PRAGMA cache_spill=ON */
12989 #define PAGER_FLAGS_MASK 0x38 /* All above except SYNCHRONOUS */
12990 
12991 /*
12992 ** The remainder of this file contains the declarations of the functions
12993 ** that make up the Pager sub-system API. See source code comments for
12994 ** a detailed description of each routine.
12995 */
12996 
12997 /* Open and close a Pager connection. */
12998 SQLITE_PRIVATE int sqlite3PagerOpen(
12999  sqlite3_vfs*,
13000  Pager **ppPager,
13001  const char*,
13002  int,
13003  int,
13004  int,
13005  void(*)(DbPage*)
13006 );
13007 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
13008 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
13009 
13010 /* Functions used to configure a Pager object. */
13011 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
13012 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
13013 #ifdef SQLITE_HAS_CODEC
13014 SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
13015 #endif
13016 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
13017 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
13018 SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
13019 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
13020 SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
13021 SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
13022 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
13023 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
13024 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
13025 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
13026 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
13027 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
13028 SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
13029 
13030 /* Functions used to obtain and release page references. */
13031 SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
13032 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
13033 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
13034 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
13035 SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
13036 
13037 /* Operations on page references. */
13038 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
13039 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
13040 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
13041 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
13042 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
13043 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
13044 
13045 /* Functions used to manage pager transactions and savepoints. */
13046 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
13047 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
13048 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
13049 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
13050 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
13051 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
13052 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
13053 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
13054 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
13055 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
13056 
13057 #ifndef SQLITE_OMIT_WAL
13058 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
13059 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
13060 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
13061 SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
13062 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
13063 # ifdef SQLITE_ENABLE_SNAPSHOT
13064 SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot);
13065 SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot);
13066 # endif
13067 #endif
13068 
13069 #ifdef SQLITE_ENABLE_ZIPVFS
13070 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
13071 #endif
13072 
13073 /* Functions used to query pager state and configuration. */
13074 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
13075 SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
13076 #ifdef SQLITE_DEBUG
13077 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
13078 #endif
13079 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
13080 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
13081 SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
13082 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
13083 SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
13084 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
13085 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
13086 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
13087 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
13088 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);
13089 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
13090 
13091 /* Functions used to truncate the database file. */
13092 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
13093 
13094 SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
13095 
13096 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
13097 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
13098 #endif
13099 
13100 /* Functions to support testing and debugging. */
13101 #if !defined(NDEBUG) || defined(SQLITE_TEST)
13102 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
13103 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
13104 #endif
13105 #ifdef SQLITE_TEST
13106 SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
13107 SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
13108  void disable_simulated_io_errors(void);
13109  void enable_simulated_io_errors(void);
13110 #else
13111 # define disable_simulated_io_errors()
13112 # define enable_simulated_io_errors()
13113 #endif
13114 
13115 #endif /* SQLITE_PAGER_H */
13116 
13117 /************** End of pager.h ***********************************************/
13118 /************** Continuing where we left off in sqliteInt.h ******************/
13119 /************** Include pcache.h in the middle of sqliteInt.h ****************/
13120 /************** Begin file pcache.h ******************************************/
13121 /*
13122 ** 2008 August 05
13123 **
13124 ** The author disclaims copyright to this source code. In place of
13125 ** a legal notice, here is a blessing:
13126 **
13127 ** May you do good and not evil.
13128 ** May you find forgiveness for yourself and forgive others.
13129 ** May you share freely, never taking more than you give.
13130 **
13131 *************************************************************************
13132 ** This header file defines the interface that the sqlite page cache
13133 ** subsystem.
13134 */
13135 
13136 #ifndef _PCACHE_H_
13137 
13138 typedef struct PgHdr PgHdr;
13139 typedef struct PCache PCache;
13140 
13141 /*
13142 ** Every page in the cache is controlled by an instance of the following
13143 ** structure.
13144 */
13145 struct PgHdr {
13146  sqlite3_pcache_page *pPage; /* Pcache object page handle */
13147  void *pData; /* Page data */
13148  void *pExtra; /* Extra content */
13149  PgHdr *pDirty; /* Transient list of dirty sorted by pgno */
13150  Pager *pPager; /* The pager this page is part of */
13151  Pgno pgno; /* Page number for this page */
13152 #ifdef SQLITE_CHECK_PAGES
13153  u32 pageHash; /* Hash of page content */
13154 #endif
13155  u16 flags; /* PGHDR flags defined below */
13156 
13157  /**********************************************************************
13158  ** Elements above are public. All that follows is private to pcache.c
13159  ** and should not be accessed by other modules.
13160  */
13161  i16 nRef; /* Number of users of this page */
13162  PCache *pCache; /* Cache that owns this page */
13163 
13164  PgHdr *pDirtyNext; /* Next element in list of dirty pages */
13165  PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
13166 };
13167 
13168 /* Bit values for PgHdr.flags */
13169 #define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */
13170 #define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */
13171 #define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */
13172 #define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before
13173  ** writing this page to the database */
13174 #define PGHDR_DONT_WRITE 0x010 /* Do not write content to disk */
13175 #define PGHDR_MMAP 0x020 /* This is an mmap page object */
13176 
13177 #define PGHDR_WAL_APPEND 0x040 /* Appended to wal file */
13178 
13179 /* Initialize and shutdown the page cache subsystem */
13180 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
13181 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
13182 
13183 /* Page cache buffer management:
13184 ** These routines implement SQLITE_CONFIG_PAGECACHE.
13185 */
13186 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
13187 
13188 /* Create a new pager cache.
13189 ** Under memory stress, invoke xStress to try to make pages clean.
13190 ** Only clean and unpinned pages can be reclaimed.
13191 */
13192 SQLITE_PRIVATE int sqlite3PcacheOpen(
13193  int szPage, /* Size of every page */
13194  int szExtra, /* Extra space associated with each page */
13195  int bPurgeable, /* True if pages are on backing store */
13196  int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
13197  void *pStress, /* Argument to xStress */
13198  PCache *pToInit /* Preallocated space for the PCache */
13199 );
13200 
13201 /* Modify the page-size after the cache has been created. */
13202 SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
13203 
13204 /* Return the size in bytes of a PCache object. Used to preallocate
13205 ** storage space.
13206 */
13207 SQLITE_PRIVATE int sqlite3PcacheSize(void);
13208 
13209 /* One release per successful fetch. Page is pinned until released.
13210 ** Reference counted.
13211 */
13212 SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
13213 SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
13214 SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
13215 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
13216 
13217 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
13218 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
13219 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
13220 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
13221 SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);
13222 
13223 /* Change a page number. Used by incr-vacuum. */
13224 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
13225 
13226 /* Remove all pages with pgno>x. Reset the cache if x==0 */
13227 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
13228 
13229 /* Get a list of all dirty pages in the cache, sorted by page number */
13230 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
13231 
13232 /* Reset and close the cache object */
13233 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
13234 
13235 /* Clear flags from pages of the page cache */
13236 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
13237 
13238 /* Discard the contents of the cache */
13239 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
13240 
13241 /* Return the total number of outstanding page references */
13242 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
13243 
13244 /* Increment the reference count of an existing page */
13245 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
13246 
13247 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
13248 
13249 /* Return the total number of pages stored in the cache */
13250 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
13251 
13252 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
13253 /* Iterate through all dirty pages currently stored in the cache. This
13254 ** interface is only available if SQLITE_CHECK_PAGES is defined when the
13255 ** library is built.
13256 */
13257 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
13258 #endif
13259 
13260 #if defined(SQLITE_DEBUG)
13261 /* Check invariants on a PgHdr object */
13262 SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);
13263 #endif
13264 
13265 /* Set and get the suggested cache-size for the specified pager-cache.
13266 **
13267 ** If no global maximum is configured, then the system attempts to limit
13268 ** the total number of pages cached by purgeable pager-caches to the sum
13269 ** of the suggested cache-sizes.
13270 */
13271 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
13272 #ifdef SQLITE_TEST
13273 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
13274 #endif
13275 
13276 /* Set or get the suggested spill-size for the specified pager-cache.
13277 **
13278 ** The spill-size is the minimum number of pages in cache before the cache
13279 ** will attempt to spill dirty pages by calling xStress.
13280 */
13281 SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);
13282 
13283 /* Free up as much memory as possible from the page cache */
13284 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
13285 
13286 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
13287 /* Try to return memory used by the pcache module to the main memory heap */
13288 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
13289 #endif
13290 
13291 #ifdef SQLITE_TEST
13292 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
13293 #endif
13294 
13295 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
13296 
13297 /* Return the header size */
13298 SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
13299 SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
13300 
13301 /* Number of dirty pages as a percentage of the configured cache size */
13302 SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);
13303 
13304 #endif /* _PCACHE_H_ */
13305 
13306 /************** End of pcache.h **********************************************/
13307 /************** Continuing where we left off in sqliteInt.h ******************/
13308 /************** Include os.h in the middle of sqliteInt.h ********************/
13309 /************** Begin file os.h **********************************************/
13310 /*
13311 ** 2001 September 16
13312 **
13313 ** The author disclaims copyright to this source code. In place of
13314 ** a legal notice, here is a blessing:
13315 **
13316 ** May you do good and not evil.
13317 ** May you find forgiveness for yourself and forgive others.
13318 ** May you share freely, never taking more than you give.
13319 **
13320 ******************************************************************************
13321 **
13322 ** This header file (together with is companion C source-code file
13323 ** "os.c") attempt to abstract the underlying operating system so that
13324 ** the SQLite library will work on both POSIX and windows systems.
13325 **
13326 ** This header file is #include-ed by sqliteInt.h and thus ends up
13327 ** being included by every source file.
13328 */
13329 #ifndef _SQLITE_OS_H_
13330 #define _SQLITE_OS_H_
13331 
13332 /*
13333 ** Attempt to automatically detect the operating system and setup the
13334 ** necessary pre-processor macros for it.
13335 */
13336 /************** Include os_setup.h in the middle of os.h *********************/
13337 /************** Begin file os_setup.h ****************************************/
13338 /*
13339 ** 2013 November 25
13340 **
13341 ** The author disclaims copyright to this source code. In place of
13342 ** a legal notice, here is a blessing:
13343 **
13344 ** May you do good and not evil.
13345 ** May you find forgiveness for yourself and forgive others.
13346 ** May you share freely, never taking more than you give.
13347 **
13348 ******************************************************************************
13349 **
13350 ** This file contains pre-processor directives related to operating system
13351 ** detection and/or setup.
13352 */
13353 #ifndef SQLITE_OS_SETUP_H
13354 #define SQLITE_OS_SETUP_H
13355 
13356 /*
13357 ** Figure out if we are dealing with Unix, Windows, or some other operating
13358 ** system.
13359 **
13360 ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
13361 ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
13362 ** the three will be 1. The other two will be 0.
13363 */
13364 #if defined(SQLITE_OS_OTHER)
13365 # if SQLITE_OS_OTHER==1
13366 # undef SQLITE_OS_UNIX
13367 # define SQLITE_OS_UNIX 0
13368 # undef SQLITE_OS_WIN
13369 # define SQLITE_OS_WIN 0
13370 # else
13371 # undef SQLITE_OS_OTHER
13372 # endif
13373 #endif
13374 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
13375 # define SQLITE_OS_OTHER 0
13376 # ifndef SQLITE_OS_WIN
13377 # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
13378  defined(__MINGW32__) || defined(__BORLANDC__)
13379 # define SQLITE_OS_WIN 1
13380 # define SQLITE_OS_UNIX 0
13381 # else
13382 # define SQLITE_OS_WIN 0
13383 # define SQLITE_OS_UNIX 1
13384 # endif
13385 # else
13386 # define SQLITE_OS_UNIX 0
13387 # endif
13388 #else
13389 # ifndef SQLITE_OS_WIN
13390 # define SQLITE_OS_WIN 0
13391 # endif
13392 #endif
13393 
13394 #endif /* SQLITE_OS_SETUP_H */
13395 
13396 /************** End of os_setup.h ********************************************/
13397 /************** Continuing where we left off in os.h *************************/
13398 
13399 /* If the SET_FULLSYNC macro is not defined above, then make it
13400 ** a no-op
13401 */
13402 #ifndef SET_FULLSYNC
13403 # define SET_FULLSYNC(x,y)
13404 #endif
13405 
13406 /*
13407 ** The default size of a disk sector
13408 */
13409 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
13410 # define SQLITE_DEFAULT_SECTOR_SIZE 4096
13411 #endif
13412 
13413 /*
13414 ** Temporary files are named starting with this prefix followed by 16 random
13415 ** alphanumeric characters, and no file extension. They are stored in the
13416 ** OS's standard temporary file directory, and are deleted prior to exit.
13417 ** If sqlite is being embedded in another program, you may wish to change the
13418 ** prefix to reflect your program's name, so that if your program exits
13419 ** prematurely, old temporary files can be easily identified. This can be done
13420 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
13421 **
13422 ** 2006-10-31: The default prefix used to be "sqlite_". But then
13423 ** Mcafee started using SQLite in their anti-virus product and it
13424 ** started putting files with the "sqlite" name in the c:/temp folder.
13425 ** This annoyed many windows users. Those users would then do a
13426 ** Google search for "sqlite", find the telephone numbers of the
13427 ** developers and call to wake them up at night and complain.
13428 ** For this reason, the default name prefix is changed to be "sqlite"
13429 ** spelled backwards. So the temp files are still identified, but
13430 ** anybody smart enough to figure out the code is also likely smart
13431 ** enough to know that calling the developer will not help get rid
13432 ** of the file.
13433 */
13434 #ifndef SQLITE_TEMP_FILE_PREFIX
13435 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
13436 #endif
13437 
13438 /*
13439 ** The following values may be passed as the second argument to
13440 ** sqlite3OsLock(). The various locks exhibit the following semantics:
13441 **
13442 ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
13443 ** RESERVED: A single process may hold a RESERVED lock on a file at
13444 ** any time. Other processes may hold and obtain new SHARED locks.
13445 ** PENDING: A single process may hold a PENDING lock on a file at
13446 ** any one time. Existing SHARED locks may persist, but no new
13447 ** SHARED locks may be obtained by other processes.
13448 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
13449 **
13450 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
13451 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
13452 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
13453 ** sqlite3OsLock().
13454 */
13455 #define NO_LOCK 0
13456 #define SHARED_LOCK 1
13457 #define RESERVED_LOCK 2
13458 #define PENDING_LOCK 3
13459 #define EXCLUSIVE_LOCK 4
13460 
13461 /*
13462 ** File Locking Notes: (Mostly about windows but also some info for Unix)
13463 **
13464 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
13465 ** those functions are not available. So we use only LockFile() and
13466 ** UnlockFile().
13467 **
13468 ** LockFile() prevents not just writing but also reading by other processes.
13469 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
13470 ** byte out of a specific range of bytes. The lock byte is obtained at
13471 ** random so two separate readers can probably access the file at the
13472 ** same time, unless they are unlucky and choose the same lock byte.
13473 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
13474 ** There can only be one writer. A RESERVED_LOCK is obtained by locking
13475 ** a single byte of the file that is designated as the reserved lock byte.
13476 ** A PENDING_LOCK is obtained by locking a designated byte different from
13477 ** the RESERVED_LOCK byte.
13478 **
13479 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
13480 ** which means we can use reader/writer locks. When reader/writer locks
13481 ** are used, the lock is placed on the same range of bytes that is used
13482 ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
13483 ** will support two or more Win95 readers or two or more WinNT readers.
13484 ** But a single Win95 reader will lock out all WinNT readers and a single
13485 ** WinNT reader will lock out all other Win95 readers.
13486 **
13487 ** The following #defines specify the range of bytes used for locking.
13488 ** SHARED_SIZE is the number of bytes available in the pool from which
13489 ** a random byte is selected for a shared lock. The pool of bytes for
13490 ** shared locks begins at SHARED_FIRST.
13491 **
13492 ** The same locking strategy and
13493 ** byte ranges are used for Unix. This leaves open the possibility of having
13494 ** clients on win95, winNT, and unix all talking to the same shared file
13495 ** and all locking correctly. To do so would require that samba (or whatever
13496 ** tool is being used for file sharing) implements locks correctly between
13497 ** windows and unix. I'm guessing that isn't likely to happen, but by
13498 ** using the same locking range we are at least open to the possibility.
13499 **
13500 ** Locking in windows is manditory. For this reason, we cannot store
13501 ** actual data in the bytes used for locking. The pager never allocates
13502 ** the pages involved in locking therefore. SHARED_SIZE is selected so
13503 ** that all locks will fit on a single page even at the minimum page size.
13504 ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
13505 ** is set high so that we don't have to allocate an unused page except
13506 ** for very large databases. But one should test the page skipping logic
13507 ** by setting PENDING_BYTE low and running the entire regression suite.
13508 **
13509 ** Changing the value of PENDING_BYTE results in a subtly incompatible
13510 ** file format. Depending on how it is changed, you might not notice
13511 ** the incompatibility right away, even running a full regression test.
13512 ** The default location of PENDING_BYTE is the first byte past the
13513 ** 1GB boundary.
13514 **
13515 */
13516 #ifdef SQLITE_OMIT_WSD
13517 # define PENDING_BYTE (0x40000000)
13518 #else
13519 # define PENDING_BYTE sqlite3PendingByte
13520 #endif
13521 #define RESERVED_BYTE (PENDING_BYTE+1)
13522 #define SHARED_FIRST (PENDING_BYTE+2)
13523 #define SHARED_SIZE 510
13524 
13525 /*
13526 ** Wrapper around OS specific sqlite3_os_init() function.
13527 */
13528 SQLITE_PRIVATE int sqlite3OsInit(void);
13529 
13530 /*
13531 ** Functions for accessing sqlite3_file methods
13532 */
13533 SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
13534 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
13535 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
13536 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
13537 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
13538 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
13539 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
13540 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
13541 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
13542 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
13543 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
13544 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
13545 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
13546 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
13547 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
13548 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
13549 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
13550 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
13551 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
13552 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
13553 
13554 
13555 /*
13556 ** Functions for accessing sqlite3_vfs methods
13557 */
13558 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
13559 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
13560 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
13561 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
13562 #ifndef SQLITE_OMIT_LOAD_EXTENSION
13563 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
13564 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
13565 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
13566 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
13567 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
13568 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
13569 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
13570 SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
13571 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
13572 
13573 /*
13574 ** Convenience functions for opening and closing files using
13575 ** sqlite3_malloc() to obtain space for the file-handle structure.
13576 */
13577 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
13578 SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
13579 
13580 #endif /* _SQLITE_OS_H_ */
13581 
13582 /************** End of os.h **************************************************/
13583 /************** Continuing where we left off in sqliteInt.h ******************/
13584 /************** Include mutex.h in the middle of sqliteInt.h *****************/
13585 /************** Begin file mutex.h *******************************************/
13586 /*
13587 ** 2007 August 28
13588 **
13589 ** The author disclaims copyright to this source code. In place of
13590 ** a legal notice, here is a blessing:
13591 **
13592 ** May you do good and not evil.
13593 ** May you find forgiveness for yourself and forgive others.
13594 ** May you share freely, never taking more than you give.
13595 **
13596 *************************************************************************
13597 **
13598 ** This file contains the common header for all mutex implementations.
13599 ** The sqliteInt.h header #includes this file so that it is available
13600 ** to all source files. We break it out in an effort to keep the code
13601 ** better organized.
13602 **
13603 ** NOTE: source files should *not* #include this header file directly.
13604 ** Source files should #include the sqliteInt.h file and let that file
13605 ** include this one indirectly.
13606 */
13607 
13608 
13609 /*
13610 ** Figure out what version of the code to use. The choices are
13611 **
13612 ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
13613 ** mutexes implementation cannot be overridden
13614 ** at start-time.
13615 **
13616 ** SQLITE_MUTEX_NOOP For single-threaded applications. No
13617 ** mutual exclusion is provided. But this
13618 ** implementation can be overridden at
13619 ** start-time.
13620 **
13621 ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
13622 **
13623 ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
13624 */
13625 #if !SQLITE_THREADSAFE
13626 # define SQLITE_MUTEX_OMIT
13627 #endif
13628 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
13629 # if SQLITE_OS_UNIX
13630 # define SQLITE_MUTEX_PTHREADS
13631 # elif SQLITE_OS_WIN
13632 # define SQLITE_MUTEX_W32
13633 # else
13634 # define SQLITE_MUTEX_NOOP
13635 # endif
13636 #endif
13637 
13638 #ifdef SQLITE_MUTEX_OMIT
13639 /*
13640 ** If this is a no-op implementation, implement everything as macros.
13641 */
13642 #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
13643 #define sqlite3_mutex_free(X)
13644 #define sqlite3_mutex_enter(X)
13645 #define sqlite3_mutex_try(X) SQLITE_OK
13646 #define sqlite3_mutex_leave(X)
13647 #define sqlite3_mutex_held(X) ((void)(X),1)
13648 #define sqlite3_mutex_notheld(X) ((void)(X),1)
13649 #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
13650 #define sqlite3MutexInit() SQLITE_OK
13651 #define sqlite3MutexEnd()
13652 #define MUTEX_LOGIC(X)
13653 #else
13654 #define MUTEX_LOGIC(X) X
13655 #endif /* defined(SQLITE_MUTEX_OMIT) */
13656 
13657 /************** End of mutex.h ***********************************************/
13658 /************** Continuing where we left off in sqliteInt.h ******************/
13659 
13660 /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
13661 ** synchronous setting to EXTRA. It is no longer supported.
13662 */
13663 #ifdef SQLITE_EXTRA_DURABLE
13664 # warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
13665 # define SQLITE_DEFAULT_SYNCHRONOUS 3
13666 #endif
13667 
13668 /*
13669 ** Default synchronous levels.
13670 **
13671 ** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
13672 ** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
13673 **
13674 ** PAGER_SYNCHRONOUS DEFAULT_SYNCHRONOUS
13675 ** OFF 1 0
13676 ** NORMAL 2 1
13677 ** FULL 3 2
13678 ** EXTRA 4 3
13679 **
13680 ** The "PRAGMA synchronous" statement also uses the zero-based numbers.
13681 ** In other words, the zero-based numbers are used for all external interfaces
13682 ** and the one-based values are used internally.
13683 */
13684 #ifndef SQLITE_DEFAULT_SYNCHRONOUS
13685 # define SQLITE_DEFAULT_SYNCHRONOUS (PAGER_SYNCHRONOUS_FULL-1)
13686 #endif
13687 #ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
13688 # define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
13689 #endif
13690 
13691 /*
13692 ** Each database file to be accessed by the system is an instance
13693 ** of the following structure. There are normally two of these structures
13694 ** in the sqlite.aDb[] array. aDb[0] is the main database file and
13695 ** aDb[1] is the database file used to hold temporary tables. Additional
13696 ** databases may be attached.
13697 */
13698 struct Db {
13699  char *zName; /* Name of this database */
13700  Btree *pBt; /* The B*Tree structure for this database file */
13701  u8 safety_level; /* How aggressive at syncing data to disk */
13702  u8 bSyncSet; /* True if "PRAGMA synchronous=N" has been run */
13703  Schema *pSchema; /* Pointer to database schema (possibly shared) */
13704 };
13705 
13706 /*
13707 ** An instance of the following structure stores a database schema.
13708 **
13709 ** Most Schema objects are associated with a Btree. The exception is
13710 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
13711 ** In shared cache mode, a single Schema object can be shared by multiple
13712 ** Btrees that refer to the same underlying BtShared object.
13713 **
13714 ** Schema objects are automatically deallocated when the last Btree that
13715 ** references them is destroyed. The TEMP Schema is manually freed by
13716 ** sqlite3_close().
13717 *
13718 ** A thread must be holding a mutex on the corresponding Btree in order
13719 ** to access Schema content. This implies that the thread must also be
13720 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
13721 ** For a TEMP Schema, only the connection mutex is required.
13722 */
13723 struct Schema {
13724  int schema_cookie; /* Database schema version number for this file */
13725  int iGeneration; /* Generation counter. Incremented with each change */
13726  Hash tblHash; /* All tables indexed by name */
13727  Hash idxHash; /* All (named) indices indexed by name */
13728  Hash trigHash; /* All triggers indexed by name */
13729  Hash fkeyHash; /* All foreign keys by referenced table name */
13730  Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
13731  u8 file_format; /* Schema format version for this file */
13732  u8 enc; /* Text encoding used by this database */
13733  u16 schemaFlags; /* Flags associated with this schema */
13734  int cache_size; /* Number of pages to use in the cache */
13735 };
13736 
13737 /*
13738 ** These macros can be used to test, set, or clear bits in the
13739 ** Db.pSchema->flags field.
13740 */
13741 #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
13742 #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
13743 #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
13744 #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
13745 
13746 /*
13747 ** Allowed values for the DB.pSchema->flags field.
13748 **
13749 ** The DB_SchemaLoaded flag is set after the database schema has been
13750 ** read into internal hash tables.
13751 **
13752 ** DB_UnresetViews means that one or more views have column names that
13753 ** have been filled out. If the schema changes, these column names might
13754 ** changes and so the view will need to be reset.
13755 */
13756 #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
13757 #define DB_UnresetViews 0x0002 /* Some views have defined column names */
13758 #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
13759 
13760 /*
13761 ** The number of different kinds of things that can be limited
13762 ** using the sqlite3_limit() interface.
13763 */
13764 #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
13765 
13766 /*
13767 ** Lookaside malloc is a set of fixed-size buffers that can be used
13768 ** to satisfy small transient memory allocation requests for objects
13769 ** associated with a particular database connection. The use of
13770 ** lookaside malloc provides a significant performance enhancement
13771 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
13772 ** SQL statements.
13773 **
13774 ** The Lookaside structure holds configuration information about the
13775 ** lookaside malloc subsystem. Each available memory allocation in
13776 ** the lookaside subsystem is stored on a linked list of LookasideSlot
13777 ** objects.
13778 **
13779 ** Lookaside allocations are only allowed for objects that are associated
13780 ** with a particular database connection. Hence, schema information cannot
13781 ** be stored in lookaside because in shared cache mode the schema information
13782 ** is shared by multiple database connections. Therefore, while parsing
13783 ** schema information, the Lookaside.bEnabled flag is cleared so that
13784 ** lookaside allocations are not used to construct the schema objects.
13785 */
13786 struct Lookaside {
13787  u32 bDisable; /* Only operate the lookaside when zero */
13788  u16 sz; /* Size of each buffer in bytes */
13789  u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
13790  int nOut; /* Number of buffers currently checked out */
13791  int mxOut; /* Highwater mark for nOut */
13792  int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
13793  LookasideSlot *pFree; /* List of available buffers */
13794  void *pStart; /* First byte of available memory space */
13795  void *pEnd; /* First byte past end of available space */
13796 };
13797 struct LookasideSlot {
13798  LookasideSlot *pNext; /* Next buffer in the list of free buffers */
13799 };
13800 
13801 /*
13802 ** A hash table for built-in function definitions. (Application-defined
13803 ** functions use a regular table table from hash.h.)
13804 **
13805 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
13806 ** Collisions are on the FuncDef.u.pHash chain.
13807 */
13808 #define SQLITE_FUNC_HASH_SZ 23
13809 struct FuncDefHash {
13810  FuncDef *a[SQLITE_FUNC_HASH_SZ]; /* Hash table for functions */
13811 };
13812 
13813 #ifdef SQLITE_USER_AUTHENTICATION
13814 /*
13815 ** Information held in the "sqlite3" database connection object and used
13816 ** to manage user authentication.
13817 */
13818 typedef struct sqlite3_userauth sqlite3_userauth;
13819 struct sqlite3_userauth {
13820  u8 authLevel; /* Current authentication level */
13821  int nAuthPW; /* Size of the zAuthPW in bytes */
13822  char *zAuthPW; /* Password used to authenticate */
13823  char *zAuthUser; /* User name used to authenticate */
13824 };
13825 
13826 /* Allowed values for sqlite3_userauth.authLevel */
13827 #define UAUTH_Unknown 0 /* Authentication not yet checked */
13828 #define UAUTH_Fail 1 /* User authentication failed */
13829 #define UAUTH_User 2 /* Authenticated as a normal user */
13830 #define UAUTH_Admin 3 /* Authenticated as an administrator */
13831 
13832 /* Functions used only by user authorization logic */
13833 SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
13834 SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
13835 SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
13836 SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
13837 
13838 #endif /* SQLITE_USER_AUTHENTICATION */
13839 
13840 /*
13841 ** typedef for the authorization callback function.
13842 */
13843 #ifdef SQLITE_USER_AUTHENTICATION
13844  typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
13845  const char*, const char*);
13846 #else
13847  typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
13848  const char*);
13849 #endif
13850 
13851 #ifndef SQLITE_OMIT_DEPRECATED
13852 /* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
13853 ** in the style of sqlite3_trace()
13854 */
13855 #define SQLITE_TRACE_LEGACY 0x80
13856 #else
13857 #define SQLITE_TRACE_LEGACY 0
13858 #endif /* SQLITE_OMIT_DEPRECATED */
13859 
13860 
13861 /*
13862 ** Each database connection is an instance of the following structure.
13863 */
13864 struct sqlite3 {
13865  sqlite3_vfs *pVfs; /* OS Interface */
13866  struct Vdbe *pVdbe; /* List of active virtual machines */
13867  CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
13868  sqlite3_mutex *mutex; /* Connection mutex */
13869  Db *aDb; /* All backends */
13870  int nDb; /* Number of backends currently in use */
13871  int flags; /* Miscellaneous flags. See below */
13872  i64 lastRowid; /* ROWID of most recent insert (see above) */
13873  i64 szMmap; /* Default mmap_size setting */
13874  unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
13875  int errCode; /* Most recent error code (SQLITE_*) */
13876  int errMask; /* & result codes with this before returning */
13877  int iSysErrno; /* Errno value from last system error */
13878  u16 dbOptFlags; /* Flags to enable/disable optimizations */
13879  u8 enc; /* Text encoding */
13880  u8 autoCommit; /* The auto-commit flag. */
13881  u8 temp_store; /* 1: file 2: memory 0: default */
13882  u8 mallocFailed; /* True if we have seen a malloc failure */
13883  u8 bBenignMalloc; /* Do not require OOMs if true */
13884  u8 dfltLockMode; /* Default locking-mode for attached dbs */
13885  signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
13886  u8 suppressErr; /* Do not issue error messages if true */
13887  u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
13888  u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
13889  u8 mTrace; /* zero or more SQLITE_TRACE flags */
13890  int nextPagesize; /* Pagesize after VACUUM if >0 */
13891  u32 magic; /* Magic number for detect library misuse */
13892  int nChange; /* Value returned by sqlite3_changes() */
13893  int nTotalChange; /* Value returned by sqlite3_total_changes() */
13894  int aLimit[SQLITE_N_LIMIT]; /* Limits */
13895  int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
13896  struct sqlite3InitInfo { /* Information used during initialization */
13897  int newTnum; /* Rootpage of table being initialized */
13898  u8 iDb; /* Which db file is being initialized */
13899  u8 busy; /* TRUE if currently initializing */
13900  u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
13901  u8 imposterTable; /* Building an imposter table */
13902  } init;
13903  int nVdbeActive; /* Number of VDBEs currently running */
13904  int nVdbeRead; /* Number of active VDBEs that read or write */
13905  int nVdbeWrite; /* Number of active VDBEs that read and write */
13906  int nVdbeExec; /* Number of nested calls to VdbeExec() */
13907  int nVDestroy; /* Number of active OP_VDestroy operations */
13908  int nExtension; /* Number of loaded extensions */
13909  void **aExtension; /* Array of shared library handles */
13910  int (*xTrace)(u32,void*,void*,void*); /* Trace function */
13911  void *pTraceArg; /* Argument to the trace function */
13912  void (*xProfile)(void*,const char*,u64); /* Profiling function */
13913  void *pProfileArg; /* Argument to profile function */
13914  void *pCommitArg; /* Argument to xCommitCallback() */
13915  int (*xCommitCallback)(void*); /* Invoked at every commit. */
13916  void *pRollbackArg; /* Argument to xRollbackCallback() */
13917  void (*xRollbackCallback)(void*); /* Invoked at every commit. */
13918  void *pUpdateArg;
13919  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
13920 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
13921  void *pPreUpdateArg; /* First argument to xPreUpdateCallback */
13922  void (*xPreUpdateCallback)( /* Registered using sqlite3_preupdate_hook() */
13923  void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
13924  );
13925  PreUpdate *pPreUpdate; /* Context for active pre-update callback */
13926 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
13927 #ifndef SQLITE_OMIT_WAL
13928  int (*xWalCallback)(void *, sqlite3 *, const char *, int);
13929  void *pWalArg;
13930 #endif
13931  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
13932  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
13933  void *pCollNeededArg;
13934  sqlite3_value *pErr; /* Most recent error message */
13935  union {
13936  volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
13937  double notUsed1; /* Spacer */
13938  } u1;
13939  Lookaside lookaside; /* Lookaside malloc configuration */
13940 #ifndef SQLITE_OMIT_AUTHORIZATION
13941  sqlite3_xauth xAuth; /* Access authorization function */
13942  void *pAuthArg; /* 1st argument to the access auth function */
13943 #endif
13944 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
13945  int (*xProgress)(void *); /* The progress callback */
13946  void *pProgressArg; /* Argument to the progress callback */
13947  unsigned nProgressOps; /* Number of opcodes for progress callback */
13948 #endif
13949 #ifndef SQLITE_OMIT_VIRTUALTABLE
13950  int nVTrans; /* Allocated size of aVTrans */
13951  Hash aModule; /* populated by sqlite3_create_module() */
13952  VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
13953  VTable **aVTrans; /* Virtual tables with open transactions */
13954  VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
13955 #endif
13956  Hash aFunc; /* Hash table of connection functions */
13957  Hash aCollSeq; /* All collating sequences */
13958  BusyHandler busyHandler; /* Busy callback */
13959  Db aDbStatic[2]; /* Static space for the 2 default backends */
13960  Savepoint *pSavepoint; /* List of active savepoints */
13961  int busyTimeout; /* Busy handler timeout, in msec */
13962  int nSavepoint; /* Number of non-transaction savepoints */
13963  int nStatement; /* Number of nested statement-transactions */
13964  i64 nDeferredCons; /* Net deferred constraints this transaction. */
13965  i64 nDeferredImmCons; /* Net deferred immediate constraints */
13966  int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
13967 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
13968  /* The following variables are all protected by the STATIC_MASTER
13969  ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
13970  **
13971  ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
13972  ** unlock so that it can proceed.
13973  **
13974  ** When X.pBlockingConnection==Y, that means that something that X tried
13975  ** tried to do recently failed with an SQLITE_LOCKED error due to locks
13976  ** held by Y.
13977  */
13978  sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
13979  sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
13980  void *pUnlockArg; /* Argument to xUnlockNotify */
13981  void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
13982  sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
13983 #endif
13984 #ifdef SQLITE_USER_AUTHENTICATION
13985  sqlite3_userauth auth; /* User authentication information */
13986 #endif
13987 };
13988 
13989 /*
13990 ** A macro to discover the encoding of a database.
13991 */
13992 #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
13993 #define ENC(db) ((db)->enc)
13994 
13995 /*
13996 ** Possible values for the sqlite3.flags.
13997 **
13998 ** Value constraints (enforced via assert()):
13999 ** SQLITE_FullFSync == PAGER_FULLFSYNC
14000 ** SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
14001 ** SQLITE_CacheSpill == PAGER_CACHE_SPILL
14002 */
14003 #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
14004 #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
14005 #define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */
14006 #define SQLITE_FullFSync 0x00000008 /* Use full fsync on the backend */
14007 #define SQLITE_CkptFullFSync 0x00000010 /* Use full fsync for checkpoint */
14008 #define SQLITE_CacheSpill 0x00000020 /* OK to spill pager cache */
14009 #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
14010 #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
14011  /* DELETE, or UPDATE and return */
14012  /* the count using a callback. */
14013 #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
14014  /* result set is empty */
14015 #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
14016 #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
14017 #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
14018 #define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */
14019 #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
14020 #define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */
14021 #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
14022 #define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */
14023 #define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */
14024 #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */
14025 #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */
14026 #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */
14027 #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */
14028 #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
14029 #define SQLITE_LoadExtFunc 0x00800000 /* Enable load_extension() SQL func */
14030 #define SQLITE_EnableTrigger 0x01000000 /* True to enable triggers */
14031 #define SQLITE_DeferFKs 0x02000000 /* Defer all FK constraints */
14032 #define SQLITE_QueryOnly 0x04000000 /* Disable database changes */
14033 #define SQLITE_VdbeEQP 0x08000000 /* Debug EXPLAIN QUERY PLAN */
14034 #define SQLITE_Vacuum 0x10000000 /* Currently in a VACUUM */
14035 #define SQLITE_CellSizeCk 0x20000000 /* Check btree cell sizes on load */
14036 #define SQLITE_Fts3Tokenizer 0x40000000 /* Enable fts3_tokenizer(2) */
14037 
14038 
14039 /*
14040 ** Bits of the sqlite3.dbOptFlags field that are used by the
14041 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
14042 ** selectively disable various optimizations.
14043 */
14044 #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
14045 #define SQLITE_ColumnCache 0x0002 /* Column cache */
14046 #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
14047 #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
14048 /* not used 0x0010 // Was: SQLITE_IdxRealAsInt */
14049 #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */
14050 #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */
14051 #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */
14052 #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */
14053 #define SQLITE_Transitive 0x0200 /* Transitive constraints */
14054 #define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */
14055 #define SQLITE_Stat34 0x0800 /* Use STAT3 or STAT4 data */
14056 #define SQLITE_CursorHints 0x2000 /* Add OP_CursorHint opcodes */
14057 #define SQLITE_AllOpts 0xffff /* All optimizations */
14058 
14059 /*
14060 ** Macros for testing whether or not optimizations are enabled or disabled.
14061 */
14062 #ifndef SQLITE_OMIT_BUILTIN_TEST
14063 #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
14064 #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
14065 #else
14066 #define OptimizationDisabled(db, mask) 0
14067 #define OptimizationEnabled(db, mask) 1
14068 #endif
14069 
14070 /*
14071 ** Return true if it OK to factor constant expressions into the initialization
14072 ** code. The argument is a Parse object for the code generator.
14073 */
14074 #define ConstFactorOk(P) ((P)->okConstFactor)
14075 
14076 /*
14077 ** Possible values for the sqlite.magic field.
14078 ** The numbers are obtained at random and have no special meaning, other
14079 ** than being distinct from one another.
14080 */
14081 #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
14082 #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
14083 #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
14084 #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
14085 #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
14086 #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
14087 
14088 /*
14089 ** Each SQL function is defined by an instance of the following
14090 ** structure. For global built-in functions (ex: substr(), max(), count())
14091 ** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
14092 ** For per-connection application-defined functions, a pointer to this
14093 ** structure is held in the db->aHash hash table.
14094 **
14095 ** The u.pHash field is used by the global built-ins. The u.pDestructor
14096 ** field is used by per-connection app-def functions.
14097 */
14098 struct FuncDef {
14099  i8 nArg; /* Number of arguments. -1 means unlimited */
14100  u16 funcFlags; /* Some combination of SQLITE_FUNC_* */
14101  void *pUserData; /* User data parameter */
14102  FuncDef *pNext; /* Next function with same name */
14103  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
14104  void (*xFinalize)(sqlite3_context*); /* Agg finalizer */
14105  const char *zName; /* SQL name of the function. */
14106  union {
14107  FuncDef *pHash; /* Next with a different name but the same hash */
14108  FuncDestructor *pDestructor; /* Reference counted destructor function */
14109  } u;
14110 };
14111 
14112 /*
14113 ** This structure encapsulates a user-function destructor callback (as
14114 ** configured using create_function_v2()) and a reference counter. When
14115 ** create_function_v2() is called to create a function with a destructor,
14116 ** a single object of this type is allocated. FuncDestructor.nRef is set to
14117 ** the number of FuncDef objects created (either 1 or 3, depending on whether
14118 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
14119 ** member of each of the new FuncDef objects is set to point to the allocated
14120 ** FuncDestructor.
14121 **
14122 ** Thereafter, when one of the FuncDef objects is deleted, the reference
14123 ** count on this object is decremented. When it reaches 0, the destructor
14124 ** is invoked and the FuncDestructor structure freed.
14125 */
14126 struct FuncDestructor {
14127  int nRef;
14128  void (*xDestroy)(void *);
14129  void *pUserData;
14130 };
14131 
14132 /*
14133 ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
14134 ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And
14135 ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There
14136 ** are assert() statements in the code to verify this.
14137 **
14138 ** Value constraints (enforced via assert()):
14139 ** SQLITE_FUNC_MINMAX == NC_MinMaxAgg == SF_MinMaxAgg
14140 ** SQLITE_FUNC_LENGTH == OPFLAG_LENGTHARG
14141 ** SQLITE_FUNC_TYPEOF == OPFLAG_TYPEOFARG
14142 ** SQLITE_FUNC_CONSTANT == SQLITE_DETERMINISTIC from the API
14143 ** SQLITE_FUNC_ENCMASK depends on SQLITE_UTF* macros in the API
14144 */
14145 #define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
14146 #define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */
14147 #define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
14148 #define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */
14149 #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
14150 #define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */
14151 #define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */
14152 #define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */
14153 #define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
14154 #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
14155 #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
14156 #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
14157 #define SQLITE_FUNC_SLOCHNG 0x2000 /* "Slow Change". Value constant during a
14158  ** single query - might change over time */
14159 
14160 /*
14161 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
14162 ** used to create the initializers for the FuncDef structures.
14163 **
14164 ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
14165 ** Used to create a scalar function definition of a function zName
14166 ** implemented by C function xFunc that accepts nArg arguments. The
14167 ** value passed as iArg is cast to a (void*) and made available
14168 ** as the user-data (sqlite3_user_data()) for the function. If
14169 ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
14170 **
14171 ** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
14172 ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
14173 **
14174 ** DFUNCTION(zName, nArg, iArg, bNC, xFunc)
14175 ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
14176 ** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions
14177 ** and functions like sqlite_version() that can change, but not during
14178 ** a single query.
14179 **
14180 ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
14181 ** Used to create an aggregate function definition implemented by
14182 ** the C functions xStep and xFinal. The first four parameters
14183 ** are interpreted in the same way as the first 4 parameters to
14184 ** FUNCTION().
14185 **
14186 ** LIKEFUNC(zName, nArg, pArg, flags)
14187 ** Used to create a scalar function definition of a function zName
14188 ** that accepts nArg arguments and is implemented by a call to C
14189 ** function likeFunc. Argument pArg is cast to a (void *) and made
14190 ** available as the function user-data (sqlite3_user_data()). The
14191 ** FuncDef.flags variable is set to the value passed as the flags
14192 ** parameter.
14193 */
14194 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
14195  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
14196  SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14197 #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
14198  {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
14199  SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14200 #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
14201  {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
14202  SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14203 #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
14204  {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
14205  SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14206 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
14207  {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
14208  pArg, 0, xFunc, 0, #zName, }
14209 #define LIKEFUNC(zName, nArg, arg, flags) \
14210  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
14211  (void *)arg, 0, likeFunc, 0, #zName, {0} }
14212 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
14213  {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
14214  SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
14215 #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
14216  {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
14217  SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
14218 
14219 /*
14220 ** All current savepoints are stored in a linked list starting at
14221 ** sqlite3.pSavepoint. The first element in the list is the most recently
14222 ** opened savepoint. Savepoints are added to the list by the vdbe
14223 ** OP_Savepoint instruction.
14224 */
14225 struct Savepoint {
14226  char *zName; /* Savepoint name (nul-terminated) */
14227  i64 nDeferredCons; /* Number of deferred fk violations */
14228  i64 nDeferredImmCons; /* Number of deferred imm fk. */
14229  Savepoint *pNext; /* Parent savepoint (if any) */
14230 };
14231 
14232 /*
14233 ** The following are used as the second parameter to sqlite3Savepoint(),
14234 ** and as the P1 argument to the OP_Savepoint instruction.
14235 */
14236 #define SAVEPOINT_BEGIN 0
14237 #define SAVEPOINT_RELEASE 1
14238 #define SAVEPOINT_ROLLBACK 2
14239 
14240 
14241 /*
14242 ** Each SQLite module (virtual table definition) is defined by an
14243 ** instance of the following structure, stored in the sqlite3.aModule
14244 ** hash table.
14245 */
14246 struct Module {
14247  const sqlite3_module *pModule; /* Callback pointers */
14248  const char *zName; /* Name passed to create_module() */
14249  void *pAux; /* pAux passed to create_module() */
14250  void (*xDestroy)(void *); /* Module destructor function */
14251  Table *pEpoTab; /* Eponymous table for this module */
14252 };
14253 
14254 /*
14255 ** information about each column of an SQL table is held in an instance
14256 ** of this structure.
14257 */
14258 struct Column {
14259  char *zName; /* Name of this column, \000, then the type */
14260  Expr *pDflt; /* Default value of this column */
14261  char *zColl; /* Collating sequence. If NULL, use the default */
14262  u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
14263  char affinity; /* One of the SQLITE_AFF_... values */
14264  u8 szEst; /* Estimated size of value in this column. sizeof(INT)==1 */
14265  u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
14266 };
14267 
14268 /* Allowed values for Column.colFlags:
14269 */
14270 #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
14271 #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
14272 #define COLFLAG_HASTYPE 0x0004 /* Type name follows column name */
14273 
14274 /*
14275 ** A "Collating Sequence" is defined by an instance of the following
14276 ** structure. Conceptually, a collating sequence consists of a name and
14277 ** a comparison routine that defines the order of that sequence.
14278 **
14279 ** If CollSeq.xCmp is NULL, it means that the
14280 ** collating sequence is undefined. Indices built on an undefined
14281 ** collating sequence may not be read or written.
14282 */
14283 struct CollSeq {
14284  char *zName; /* Name of the collating sequence, UTF-8 encoded */
14285  u8 enc; /* Text encoding handled by xCmp() */
14286  void *pUser; /* First argument to xCmp() */
14287  int (*xCmp)(void*,int, const void*, int, const void*);
14288  void (*xDel)(void*); /* Destructor for pUser */
14289 };
14290 
14291 /*
14292 ** A sort order can be either ASC or DESC.
14293 */
14294 #define SQLITE_SO_ASC 0 /* Sort in ascending order */
14295 #define SQLITE_SO_DESC 1 /* Sort in ascending order */
14296 #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
14297 
14298 /*
14299 ** Column affinity types.
14300 **
14301 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
14302 ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
14303 ** the speed a little by numbering the values consecutively.
14304 **
14305 ** But rather than start with 0 or 1, we begin with 'A'. That way,
14306 ** when multiple affinity types are concatenated into a string and
14307 ** used as the P4 operand, they will be more readable.
14308 **
14309 ** Note also that the numeric types are grouped together so that testing
14310 ** for a numeric type is a single comparison. And the BLOB type is first.
14311 */
14312 #define SQLITE_AFF_BLOB 'A'
14313 #define SQLITE_AFF_TEXT 'B'
14314 #define SQLITE_AFF_NUMERIC 'C'
14315 #define SQLITE_AFF_INTEGER 'D'
14316 #define SQLITE_AFF_REAL 'E'
14317 
14318 #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
14319 
14320 /*
14321 ** The SQLITE_AFF_MASK values masks off the significant bits of an
14322 ** affinity value.
14323 */
14324 #define SQLITE_AFF_MASK 0x47
14325 
14326 /*
14327 ** Additional bit values that can be ORed with an affinity without
14328 ** changing the affinity.
14329 **
14330 ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
14331 ** It causes an assert() to fire if either operand to a comparison
14332 ** operator is NULL. It is added to certain comparison operators to
14333 ** prove that the operands are always NOT NULL.
14334 */
14335 #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
14336 #define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */
14337 #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
14338 #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
14339 
14340 /*
14341 ** An object of this type is created for each virtual table present in
14342 ** the database schema.
14343 **
14344 ** If the database schema is shared, then there is one instance of this
14345 ** structure for each database connection (sqlite3*) that uses the shared
14346 ** schema. This is because each database connection requires its own unique
14347 ** instance of the sqlite3_vtab* handle used to access the virtual table
14348 ** implementation. sqlite3_vtab* handles can not be shared between
14349 ** database connections, even when the rest of the in-memory database
14350 ** schema is shared, as the implementation often stores the database
14351 ** connection handle passed to it via the xConnect() or xCreate() method
14352 ** during initialization internally. This database connection handle may
14353 ** then be used by the virtual table implementation to access real tables
14354 ** within the database. So that they appear as part of the callers
14355 ** transaction, these accesses need to be made via the same database
14356 ** connection as that used to execute SQL operations on the virtual table.
14357 **
14358 ** All VTable objects that correspond to a single table in a shared
14359 ** database schema are initially stored in a linked-list pointed to by
14360 ** the Table.pVTable member variable of the corresponding Table object.
14361 ** When an sqlite3_prepare() operation is required to access the virtual
14362 ** table, it searches the list for the VTable that corresponds to the
14363 ** database connection doing the preparing so as to use the correct
14364 ** sqlite3_vtab* handle in the compiled query.
14365 **
14366 ** When an in-memory Table object is deleted (for example when the
14367 ** schema is being reloaded for some reason), the VTable objects are not
14368 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
14369 ** immediately. Instead, they are moved from the Table.pVTable list to
14370 ** another linked list headed by the sqlite3.pDisconnect member of the
14371 ** corresponding sqlite3 structure. They are then deleted/xDisconnected
14372 ** next time a statement is prepared using said sqlite3*. This is done
14373 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
14374 ** Refer to comments above function sqlite3VtabUnlockList() for an
14375 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
14376 ** list without holding the corresponding sqlite3.mutex mutex.
14377 **
14378 ** The memory for objects of this type is always allocated by
14379 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
14380 ** the first argument.
14381 */
14382 struct VTable {
14383  sqlite3 *db; /* Database connection associated with this table */
14384  Module *pMod; /* Pointer to module implementation */
14385  sqlite3_vtab *pVtab; /* Pointer to vtab instance */
14386  int nRef; /* Number of pointers to this structure */
14387  u8 bConstraint; /* True if constraints are supported */
14388  int iSavepoint; /* Depth of the SAVEPOINT stack */
14389  VTable *pNext; /* Next in linked list (see above) */
14390 };
14391 
14392 /*
14393 ** The schema for each SQL table and view is represented in memory
14394 ** by an instance of the following structure.
14395 */
14396 struct Table {
14397  char *zName; /* Name of the table or view */
14398  Column *aCol; /* Information about each column */
14399  Index *pIndex; /* List of SQL indexes on this table. */
14400  Select *pSelect; /* NULL for tables. Points to definition if a view. */
14401  FKey *pFKey; /* Linked list of all foreign keys in this table */
14402  char *zColAff; /* String defining the affinity of each column */
14403  ExprList *pCheck; /* All CHECK constraints */
14404  /* ... also used as column name list in a VIEW */
14405  int tnum; /* Root BTree page for this table */
14406  i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */
14407  i16 nCol; /* Number of columns in this table */
14408  u16 nRef; /* Number of pointers to this Table */
14409  LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
14410  LogEst szTabRow; /* Estimated size of each table row in bytes */
14411 #ifdef SQLITE_ENABLE_COSTMULT
14412  LogEst costMult; /* Cost multiplier for using this table */
14413 #endif
14414  u8 tabFlags; /* Mask of TF_* values */
14415  u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
14416 #ifndef SQLITE_OMIT_ALTERTABLE
14417  int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
14418 #endif
14419 #ifndef SQLITE_OMIT_VIRTUALTABLE
14420  int nModuleArg; /* Number of arguments to the module */
14421  char **azModuleArg; /* 0: module 1: schema 2: vtab name 3...: args */
14422  VTable *pVTable; /* List of VTable objects. */
14423 #endif
14424  Trigger *pTrigger; /* List of triggers stored in pSchema */
14425  Schema *pSchema; /* Schema that contains this table */
14426  Table *pNextZombie; /* Next on the Parse.pZombieTab list */
14427 };
14428 
14429 /*
14430 ** Allowed values for Table.tabFlags.
14431 **
14432 ** TF_OOOHidden applies to tables or view that have hidden columns that are
14433 ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
14434 ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
14435 ** the TF_OOOHidden attribute would apply in this case. Such tables require
14436 ** special handling during INSERT processing.
14437 */
14438 #define TF_Readonly 0x01 /* Read-only system table */
14439 #define TF_Ephemeral 0x02 /* An ephemeral table */
14440 #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
14441 #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
14442 #define TF_Virtual 0x10 /* Is a virtual table */
14443 #define TF_WithoutRowid 0x20 /* No rowid. PRIMARY KEY is the key */
14444 #define TF_NoVisibleRowid 0x40 /* No user-visible "rowid" column */
14445 #define TF_OOOHidden 0x80 /* Out-of-Order hidden columns */
14446 
14447 
14448 /*
14449 ** Test to see whether or not a table is a virtual table. This is
14450 ** done as a macro so that it will be optimized out when virtual
14451 ** table support is omitted from the build.
14452 */
14453 #ifndef SQLITE_OMIT_VIRTUALTABLE
14454 # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
14455 #else
14456 # define IsVirtual(X) 0
14457 #endif
14458 
14459 /*
14460 ** Macros to determine if a column is hidden. IsOrdinaryHiddenColumn()
14461 ** only works for non-virtual tables (ordinary tables and views) and is
14462 ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined. The
14463 ** IsHiddenColumn() macro is general purpose.
14464 */
14465 #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
14466 # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
14467 # define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
14468 #elif !defined(SQLITE_OMIT_VIRTUALTABLE)
14469 # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
14470 # define IsOrdinaryHiddenColumn(X) 0
14471 #else
14472 # define IsHiddenColumn(X) 0
14473 # define IsOrdinaryHiddenColumn(X) 0
14474 #endif
14475 
14476 
14477 /* Does the table have a rowid */
14478 #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
14479 #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
14480 
14481 /*
14482 ** Each foreign key constraint is an instance of the following structure.
14483 **
14484 ** A foreign key is associated with two tables. The "from" table is
14485 ** the table that contains the REFERENCES clause that creates the foreign
14486 ** key. The "to" table is the table that is named in the REFERENCES clause.
14487 ** Consider this example:
14488 **
14489 ** CREATE TABLE ex1(
14490 ** a INTEGER PRIMARY KEY,
14491 ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
14492 ** );
14493 **
14494 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
14495 ** Equivalent names:
14496 **
14497 ** from-table == child-table
14498 ** to-table == parent-table
14499 **
14500 ** Each REFERENCES clause generates an instance of the following structure
14501 ** which is attached to the from-table. The to-table need not exist when
14502 ** the from-table is created. The existence of the to-table is not checked.
14503 **
14504 ** The list of all parents for child Table X is held at X.pFKey.
14505 **
14506 ** A list of all children for a table named Z (which might not even exist)
14507 ** is held in Schema.fkeyHash with a hash key of Z.
14508 */
14509 struct FKey {
14510  Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
14511  FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
14512  char *zTo; /* Name of table that the key points to (aka: Parent) */
14513  FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
14514  FKey *pPrevTo; /* Previous with the same zTo */
14515  int nCol; /* Number of columns in this key */
14516  /* EV: R-30323-21917 */
14517  u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
14518  u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
14519  Trigger *apTrigger[2];/* Triggers for aAction[] actions */
14520  struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
14521  int iFrom; /* Index of column in pFrom */
14522  char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
14523  } aCol[1]; /* One entry for each of nCol columns */
14524 };
14525 
14526 /*
14527 ** SQLite supports many different ways to resolve a constraint
14528 ** error. ROLLBACK processing means that a constraint violation
14529 ** causes the operation in process to fail and for the current transaction
14530 ** to be rolled back. ABORT processing means the operation in process
14531 ** fails and any prior changes from that one operation are backed out,
14532 ** but the transaction is not rolled back. FAIL processing means that
14533 ** the operation in progress stops and returns an error code. But prior
14534 ** changes due to the same operation are not backed out and no rollback
14535 ** occurs. IGNORE means that the particular row that caused the constraint
14536 ** error is not inserted or updated. Processing continues and no error
14537 ** is returned. REPLACE means that preexisting database rows that caused
14538 ** a UNIQUE constraint violation are removed so that the new insert or
14539 ** update can proceed. Processing continues and no error is reported.
14540 **
14541 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
14542 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
14543 ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
14544 ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
14545 ** referenced table row is propagated into the row that holds the
14546 ** foreign key.
14547 **
14548 ** The following symbolic values are used to record which type
14549 ** of action to take.
14550 */
14551 #define OE_None 0 /* There is no constraint to check */
14552 #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
14553 #define OE_Abort 2 /* Back out changes but do no rollback transaction */
14554 #define OE_Fail 3 /* Stop the operation but leave all prior changes */
14555 #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
14556 #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
14557 
14558 #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
14559 #define OE_SetNull 7 /* Set the foreign key value to NULL */
14560 #define OE_SetDflt 8 /* Set the foreign key value to its default */
14561 #define OE_Cascade 9 /* Cascade the changes */
14562 
14563 #define OE_Default 10 /* Do whatever the default action is */
14564 
14565 
14566 /*
14567 ** An instance of the following structure is passed as the first
14568 ** argument to sqlite3VdbeKeyCompare and is used to control the
14569 ** comparison of the two index keys.
14570 **
14571 ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
14572 ** are nField slots for the columns of an index then one extra slot
14573 ** for the rowid at the end.
14574 */
14575 struct KeyInfo {
14576  u32 nRef; /* Number of references to this KeyInfo object */
14577  u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
14578  u16 nField; /* Number of key columns in the index */
14579  u16 nXField; /* Number of columns beyond the key columns */
14580  sqlite3 *db; /* The database connection */
14581  u8 *aSortOrder; /* Sort order for each column. */
14582  CollSeq *aColl[1]; /* Collating sequence for each term of the key */
14583 };
14584 
14585 /*
14586 ** This object holds a record which has been parsed out into individual
14587 ** fields, for the purposes of doing a comparison.
14588 **
14589 ** A record is an object that contains one or more fields of data.
14590 ** Records are used to store the content of a table row and to store
14591 ** the key of an index. A blob encoding of a record is created by
14592 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
14593 ** OP_Column opcode.
14594 **
14595 ** An instance of this object serves as a "key" for doing a search on
14596 ** an index b+tree. The goal of the search is to find the entry that
14597 ** is closed to the key described by this object. This object might hold
14598 ** just a prefix of the key. The number of fields is given by
14599 ** pKeyInfo->nField.
14600 **
14601 ** The r1 and r2 fields are the values to return if this key is less than
14602 ** or greater than a key in the btree, respectively. These are normally
14603 ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
14604 ** is in DESC order.
14605 **
14606 ** The key comparison functions actually return default_rc when they find
14607 ** an equals comparison. default_rc can be -1, 0, or +1. If there are
14608 ** multiple entries in the b-tree with the same key (when only looking
14609 ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
14610 ** cause the search to find the last match, or +1 to cause the search to
14611 ** find the first match.
14612 **
14613 ** The key comparison functions will set eqSeen to true if they ever
14614 ** get and equal results when comparing this structure to a b-tree record.
14615 ** When default_rc!=0, the search might end up on the record immediately
14616 ** before the first match or immediately after the last match. The
14617 ** eqSeen field will indicate whether or not an exact match exists in the
14618 ** b-tree.
14619 */
14620 struct UnpackedRecord {
14621  KeyInfo *pKeyInfo; /* Collation and sort-order information */
14622  Mem *aMem; /* Values */
14623  u16 nField; /* Number of entries in apMem[] */
14624  i8 default_rc; /* Comparison result if keys are equal */
14625  u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
14626  i8 r1; /* Value to return if (lhs > rhs) */
14627  i8 r2; /* Value to return if (rhs < lhs) */
14628  u8 eqSeen; /* True if an equality comparison has been seen */
14629 };
14630 
14631 
14632 /*
14633 ** Each SQL index is represented in memory by an
14634 ** instance of the following structure.
14635 **
14636 ** The columns of the table that are to be indexed are described
14637 ** by the aiColumn[] field of this structure. For example, suppose
14638 ** we have the following table and index:
14639 **
14640 ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
14641 ** CREATE INDEX Ex2 ON Ex1(c3,c1);
14642 **
14643 ** In the Table structure describing Ex1, nCol==3 because there are
14644 ** three columns in the table. In the Index structure describing
14645 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
14646 ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
14647 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
14648 ** The second column to be indexed (c1) has an index of 0 in
14649 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
14650 **
14651 ** The Index.onError field determines whether or not the indexed columns
14652 ** must be unique and what to do if they are not. When Index.onError=OE_None,
14653 ** it means this is not a unique index. Otherwise it is a unique index
14654 ** and the value of Index.onError indicate the which conflict resolution
14655 ** algorithm to employ whenever an attempt is made to insert a non-unique
14656 ** element.
14657 **
14658 ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
14659 ** generate VDBE code (as opposed to parsing one read from an sqlite_master
14660 ** table as part of parsing an existing database schema), transient instances
14661 ** of this structure may be created. In this case the Index.tnum variable is
14662 ** used to store the address of a VDBE instruction, not a database page
14663 ** number (it cannot - the database page is not allocated until the VDBE
14664 ** program is executed). See convertToWithoutRowidTable() for details.
14665 */
14666 struct Index {
14667  char *zName; /* Name of this index */
14668  i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
14669  LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
14670  Table *pTable; /* The SQL table being indexed */
14671  char *zColAff; /* String defining the affinity of each column */
14672  Index *pNext; /* The next index associated with the same table */
14673  Schema *pSchema; /* Schema containing this index */
14674  u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
14675  const char **azColl; /* Array of collation sequence names for index */
14676  Expr *pPartIdxWhere; /* WHERE clause for partial indices */
14677  ExprList *aColExpr; /* Column expressions */
14678  int tnum; /* DB Page containing root of this index */
14679  LogEst szIdxRow; /* Estimated average row size in bytes */
14680  u16 nKeyCol; /* Number of columns forming the key */
14681  u16 nColumn; /* Number of columns stored in the index */
14682  u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
14683  unsigned idxType:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
14684  unsigned bUnordered:1; /* Use this index for == or IN queries only */
14685  unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
14686  unsigned isResized:1; /* True if resizeIndexObject() has been called */
14687  unsigned isCovering:1; /* True if this is a covering index */
14688  unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
14689 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
14690  int nSample; /* Number of elements in aSample[] */
14691  int nSampleCol; /* Size of IndexSample.anEq[] and so on */
14692  tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
14693  IndexSample *aSample; /* Samples of the left-most key */
14694  tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
14695  tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
14696 #endif
14697 };
14698 
14699 /*
14700 ** Allowed values for Index.idxType
14701 */
14702 #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
14703 #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
14704 #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
14705 
14706 /* Return true if index X is a PRIMARY KEY index */
14707 #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
14708 
14709 /* Return true if index X is a UNIQUE index */
14710 #define IsUniqueIndex(X) ((X)->onError!=OE_None)
14711 
14712 /* The Index.aiColumn[] values are normally positive integer. But
14713 ** there are some negative values that have special meaning:
14714 */
14715 #define XN_ROWID (-1) /* Indexed column is the rowid */
14716 #define XN_EXPR (-2) /* Indexed column is an expression */
14717 
14718 /*
14719 ** Each sample stored in the sqlite_stat3 table is represented in memory
14720 ** using a structure of this type. See documentation at the top of the
14721 ** analyze.c source file for additional information.
14722 */
14723 struct IndexSample {
14724  void *p; /* Pointer to sampled record */
14725  int n; /* Size of record in bytes */
14726  tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
14727  tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
14728  tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
14729 };
14730 
14731 /*
14732 ** Each token coming out of the lexer is an instance of
14733 ** this structure. Tokens are also used as part of an expression.
14734 **
14735 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
14736 ** may contain random values. Do not make any assumptions about Token.dyn
14737 ** and Token.n when Token.z==0.
14738 */
14739 struct Token {
14740  const char *z; /* Text of the token. Not NULL-terminated! */
14741  unsigned int n; /* Number of characters in this token */
14742 };
14743 
14744 /*
14745 ** An instance of this structure contains information needed to generate
14746 ** code for a SELECT that contains aggregate functions.
14747 **
14748 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
14749 ** pointer to this structure. The Expr.iColumn field is the index in
14750 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
14751 ** code for that node.
14752 **
14753 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
14754 ** original Select structure that describes the SELECT statement. These
14755 ** fields do not need to be freed when deallocating the AggInfo structure.
14756 */
14757 struct AggInfo {
14758  u8 directMode; /* Direct rendering mode means take data directly
14759  ** from source tables rather than from accumulators */
14760  u8 useSortingIdx; /* In direct mode, reference the sorting index rather
14761  ** than the source table */
14762  int sortingIdx; /* Cursor number of the sorting index */
14763  int sortingIdxPTab; /* Cursor number of pseudo-table */
14764  int nSortingColumn; /* Number of columns in the sorting index */
14765  int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
14766  ExprList *pGroupBy; /* The group by clause */
14767  struct AggInfo_col { /* For each column used in source tables */
14768  Table *pTab; /* Source table */
14769  int iTable; /* Cursor number of the source table */
14770  int iColumn; /* Column number within the source table */
14771  int iSorterColumn; /* Column number in the sorting index */
14772  int iMem; /* Memory location that acts as accumulator */
14773  Expr *pExpr; /* The original expression */
14774  } *aCol;
14775  int nColumn; /* Number of used entries in aCol[] */
14776  int nAccumulator; /* Number of columns that show through to the output.
14777  ** Additional columns are used only as parameters to
14778  ** aggregate functions */
14779  struct AggInfo_func { /* For each aggregate function */
14780  Expr *pExpr; /* Expression encoding the function */
14781  FuncDef *pFunc; /* The aggregate function implementation */
14782  int iMem; /* Memory location that acts as accumulator */
14783  int iDistinct; /* Ephemeral table used to enforce DISTINCT */
14784  } *aFunc;
14785  int nFunc; /* Number of entries in aFunc[] */
14786 };
14787 
14788 /*
14789 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
14790 ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
14791 ** than 32767 we have to make it 32-bit. 16-bit is preferred because
14792 ** it uses less memory in the Expr object, which is a big memory user
14793 ** in systems with lots of prepared statements. And few applications
14794 ** need more than about 10 or 20 variables. But some extreme users want
14795 ** to have prepared statements with over 32767 variables, and for them
14796 ** the option is available (at compile-time).
14797 */
14798 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
14799 typedef i16 ynVar;
14800 #else
14801 typedef int ynVar;
14802 #endif
14803 
14804 /*
14805 ** Each node of an expression in the parse tree is an instance
14806 ** of this structure.
14807 **
14808 ** Expr.op is the opcode. The integer parser token codes are reused
14809 ** as opcodes here. For example, the parser defines TK_GE to be an integer
14810 ** code representing the ">=" operator. This same integer code is reused
14811 ** to represent the greater-than-or-equal-to operator in the expression
14812 ** tree.
14813 **
14814 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
14815 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
14816 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
14817 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
14818 ** then Expr.token contains the name of the function.
14819 **
14820 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
14821 ** binary operator. Either or both may be NULL.
14822 **
14823 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
14824 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
14825 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
14826 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
14827 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
14828 ** valid.
14829 **
14830 ** An expression of the form ID or ID.ID refers to a column in a table.
14831 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
14832 ** the integer cursor number of a VDBE cursor pointing to that table and
14833 ** Expr.iColumn is the column number for the specific column. If the
14834 ** expression is used as a result in an aggregate SELECT, then the
14835 ** value is also stored in the Expr.iAgg column in the aggregate so that
14836 ** it can be accessed after all aggregates are computed.
14837 **
14838 ** If the expression is an unbound variable marker (a question mark
14839 ** character '?' in the original SQL) then the Expr.iTable holds the index
14840 ** number for that variable.
14841 **
14842 ** If the expression is a subquery then Expr.iColumn holds an integer
14843 ** register number containing the result of the subquery. If the
14844 ** subquery gives a constant result, then iTable is -1. If the subquery
14845 ** gives a different answer at different times during statement processing
14846 ** then iTable is the address of a subroutine that computes the subquery.
14847 **
14848 ** If the Expr is of type OP_Column, and the table it is selecting from
14849 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
14850 ** corresponding table definition.
14851 **
14852 ** ALLOCATION NOTES:
14853 **
14854 ** Expr objects can use a lot of memory space in database schema. To
14855 ** help reduce memory requirements, sometimes an Expr object will be
14856 ** truncated. And to reduce the number of memory allocations, sometimes
14857 ** two or more Expr objects will be stored in a single memory allocation,
14858 ** together with Expr.zToken strings.
14859 **
14860 ** If the EP_Reduced and EP_TokenOnly flags are set when
14861 ** an Expr object is truncated. When EP_Reduced is set, then all
14862 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
14863 ** are contained within the same memory allocation. Note, however, that
14864 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
14865 ** allocated, regardless of whether or not EP_Reduced is set.
14866 */
14867 struct Expr {
14868  u8 op; /* Operation performed by this node */
14869  char affinity; /* The affinity of the column or 0 if not a column */
14870  u32 flags; /* Various flags. EP_* See below */
14871  union {
14872  char *zToken; /* Token value. Zero terminated and dequoted */
14873  int iValue; /* Non-negative integer value if EP_IntValue */
14874  } u;
14875 
14876  /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
14877  ** space is allocated for the fields below this point. An attempt to
14878  ** access them will result in a segfault or malfunction.
14879  *********************************************************************/
14880 
14881  Expr *pLeft; /* Left subnode */
14882  Expr *pRight; /* Right subnode */
14883  union {
14884  ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
14885  Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
14886  } x;
14887 
14888  /* If the EP_Reduced flag is set in the Expr.flags mask, then no
14889  ** space is allocated for the fields below this point. An attempt to
14890  ** access them will result in a segfault or malfunction.
14891  *********************************************************************/
14892 
14893 #if SQLITE_MAX_EXPR_DEPTH>0
14894  int nHeight; /* Height of the tree headed by this node */
14895 #endif
14896  int iTable; /* TK_COLUMN: cursor number of table holding column
14897  ** TK_REGISTER: register number
14898  ** TK_TRIGGER: 1 -> new, 0 -> old
14899  ** EP_Unlikely: 134217728 times likelihood */
14900  ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
14901  ** TK_VARIABLE: variable number (always >= 1). */
14902  i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
14903  i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
14904  u8 op2; /* TK_REGISTER: original value of Expr.op
14905  ** TK_COLUMN: the value of p5 for OP_Column
14906  ** TK_AGG_FUNCTION: nesting depth */
14907  AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
14908  Table *pTab; /* Table for TK_COLUMN expressions. */
14909 };
14910 
14911 /*
14912 ** The following are the meanings of bits in the Expr.flags field.
14913 */
14914 #define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */
14915 #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
14916 #define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */
14917 #define EP_Error 0x000008 /* Expression contains one or more errors */
14918 #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
14919 #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
14920 #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
14921 #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
14922 #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
14923 #define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */
14924 #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
14925 #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
14926 #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
14927 #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
14928 #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
14929 #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
14930 #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
14931 #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
14932 #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
14933 #define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
14934 #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
14935 #define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */
14936 #define EP_Alias 0x400000 /* Is an alias for a result set column */
14937 
14938 /*
14939 ** Combinations of two or more EP_* flags
14940 */
14941 #define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */
14942 
14943 /*
14944 ** These macros can be used to test, set, or clear bits in the
14945 ** Expr.flags field.
14946 */
14947 #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
14948 #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
14949 #define ExprSetProperty(E,P) (E)->flags|=(P)
14950 #define ExprClearProperty(E,P) (E)->flags&=~(P)
14951 
14952 /* The ExprSetVVAProperty() macro is used for Verification, Validation,
14953 ** and Accreditation only. It works like ExprSetProperty() during VVA
14954 ** processes but is a no-op for delivery.
14955 */
14956 #ifdef SQLITE_DEBUG
14957 # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
14958 #else
14959 # define ExprSetVVAProperty(E,P)
14960 #endif
14961 
14962 /*
14963 ** Macros to determine the number of bytes required by a normal Expr
14964 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
14965 ** and an Expr struct with the EP_TokenOnly flag set.
14966 */
14967 #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
14968 #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
14969 #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
14970 
14971 /*
14972 ** Flags passed to the sqlite3ExprDup() function. See the header comment
14973 ** above sqlite3ExprDup() for details.
14974 */
14975 #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
14976 
14977 /*
14978 ** A list of expressions. Each expression may optionally have a
14979 ** name. An expr/name combination can be used in several ways, such
14980 ** as the list of "expr AS ID" fields following a "SELECT" or in the
14981 ** list of "ID = expr" items in an UPDATE. A list of expressions can
14982 ** also be used as the argument to a function, in which case the a.zName
14983 ** field is not used.
14984 **
14985 ** By default the Expr.zSpan field holds a human-readable description of
14986 ** the expression that is used in the generation of error messages and
14987 ** column labels. In this case, Expr.zSpan is typically the text of a
14988 ** column expression as it exists in a SELECT statement. However, if
14989 ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
14990 ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
14991 ** form is used for name resolution with nested FROM clauses.
14992 */
14993 struct ExprList {
14994  int nExpr; /* Number of expressions on the list */
14995  struct ExprList_item { /* For each expression in the list */
14996  Expr *pExpr; /* The list of expressions */
14997  char *zName; /* Token associated with this expression */
14998  char *zSpan; /* Original text of the expression */
14999  u8 sortOrder; /* 1 for DESC or 0 for ASC */
15000  unsigned done :1; /* A flag to indicate when processing is finished */
15001  unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
15002  unsigned reusable :1; /* Constant expression is reusable */
15003  union {
15004  struct {
15005  u16 iOrderByCol; /* For ORDER BY, column number in result set */
15006  u16 iAlias; /* Index into Parse.aAlias[] for zName */
15007  } x;
15008  int iConstExprReg; /* Register in which Expr value is cached */
15009  } u;
15010  } *a; /* Alloc a power of two greater or equal to nExpr */
15011 };
15012 
15013 /*
15014 ** An instance of this structure is used by the parser to record both
15015 ** the parse tree for an expression and the span of input text for an
15016 ** expression.
15017 */
15018 struct ExprSpan {
15019  Expr *pExpr; /* The expression parse tree */
15020  const char *zStart; /* First character of input text */
15021  const char *zEnd; /* One character past the end of input text */
15022 };
15023 
15024 /*
15025 ** An instance of this structure can hold a simple list of identifiers,
15026 ** such as the list "a,b,c" in the following statements:
15027 **
15028 ** INSERT INTO t(a,b,c) VALUES ...;
15029 ** CREATE INDEX idx ON t(a,b,c);
15030 ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
15031 **
15032 ** The IdList.a.idx field is used when the IdList represents the list of
15033 ** column names after a table name in an INSERT statement. In the statement
15034 **
15035 ** INSERT INTO t(a,b,c) ...
15036 **
15037 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
15038 */
15039 struct IdList {
15040  struct IdList_item {
15041  char *zName; /* Name of the identifier */
15042  int idx; /* Index in some Table.aCol[] of a column named zName */
15043  } *a;
15044  int nId; /* Number of identifiers on the list */
15045 };
15046 
15047 /*
15048 ** The bitmask datatype defined below is used for various optimizations.
15049 **
15050 ** Changing this from a 64-bit to a 32-bit type limits the number of
15051 ** tables in a join to 32 instead of 64. But it also reduces the size
15052 ** of the library by 738 bytes on ix86.
15053 */
15054 #ifdef SQLITE_BITMASK_TYPE
15055  typedef SQLITE_BITMASK_TYPE Bitmask;
15056 #else
15057  typedef u64 Bitmask;
15058 #endif
15059 
15060 /*
15061 ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
15062 */
15063 #define BMS ((int)(sizeof(Bitmask)*8))
15064 
15065 /*
15066 ** A bit in a Bitmask
15067 */
15068 #define MASKBIT(n) (((Bitmask)1)<<(n))
15069 #define MASKBIT32(n) (((unsigned int)1)<<(n))
15070 #define ALLBITS ((Bitmask)-1)
15071 
15072 /*
15073 ** The following structure describes the FROM clause of a SELECT statement.
15074 ** Each table or subquery in the FROM clause is a separate element of
15075 ** the SrcList.a[] array.
15076 **
15077 ** With the addition of multiple database support, the following structure
15078 ** can also be used to describe a particular table such as the table that
15079 ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
15080 ** such a table must be a simple name: ID. But in SQLite, the table can
15081 ** now be identified by a database name, a dot, then the table name: ID.ID.
15082 **
15083 ** The jointype starts out showing the join type between the current table
15084 ** and the next table on the list. The parser builds the list this way.
15085 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
15086 ** jointype expresses the join between the table and the previous table.
15087 **
15088 ** In the colUsed field, the high-order bit (bit 63) is set if the table
15089 ** contains more than 63 columns and the 64-th or later column is used.
15090 */
15091 struct SrcList {
15092  int nSrc; /* Number of tables or subqueries in the FROM clause */
15093  u32 nAlloc; /* Number of entries allocated in a[] below */
15094  struct SrcList_item {
15095  Schema *pSchema; /* Schema to which this item is fixed */
15096  char *zDatabase; /* Name of database holding this table */
15097  char *zName; /* Name of the table */
15098  char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
15099  Table *pTab; /* An SQL table corresponding to zName */
15100  Select *pSelect; /* A SELECT statement used in place of a table name */
15101  int addrFillSub; /* Address of subroutine to manifest a subquery */
15102  int regReturn; /* Register holding return address of addrFillSub */
15103  int regResult; /* Registers holding results of a co-routine */
15104  struct {
15105  u8 jointype; /* Type of join between this table and the previous */
15106  unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
15107  unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */
15108  unsigned isTabFunc :1; /* True if table-valued-function syntax */
15109  unsigned isCorrelated :1; /* True if sub-query is correlated */
15110  unsigned viaCoroutine :1; /* Implemented as a co-routine */
15111  unsigned isRecursive :1; /* True for recursive reference in WITH */
15112  } fg;
15113 #ifndef SQLITE_OMIT_EXPLAIN
15114  u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
15115 #endif
15116  int iCursor; /* The VDBE cursor number used to access this table */
15117  Expr *pOn; /* The ON clause of a join */
15118  IdList *pUsing; /* The USING clause of a join */
15119  Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
15120  union {
15121  char *zIndexedBy; /* Identifier from "INDEXED BY <zIndex>" clause */
15122  ExprList *pFuncArg; /* Arguments to table-valued-function */
15123  } u1;
15124  Index *pIBIndex; /* Index structure corresponding to u1.zIndexedBy */
15125  } a[1]; /* One entry for each identifier on the list */
15126 };
15127 
15128 /*
15129 ** Permitted values of the SrcList.a.jointype field
15130 */
15131 #define JT_INNER 0x0001 /* Any kind of inner or cross join */
15132 #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
15133 #define JT_NATURAL 0x0004 /* True for a "natural" join */
15134 #define JT_LEFT 0x0008 /* Left outer join */
15135 #define JT_RIGHT 0x0010 /* Right outer join */
15136 #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
15137 #define JT_ERROR 0x0040 /* unknown or unsupported join type */
15138 
15139 
15140 /*
15141 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
15142 ** and the WhereInfo.wctrlFlags member.
15143 **
15144 ** Value constraints (enforced via assert()):
15145 ** WHERE_USE_LIMIT == SF_FixedLimit
15146 */
15147 #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
15148 #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
15149 #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
15150 #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
15151 #define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
15152 #define WHERE_DUPLICATES_OK 0x0010 /* Ok to return a row more than once */
15153 #define WHERE_OR_SUBCLAUSE 0x0020 /* Processing a sub-WHERE as part of
15154  ** the OR optimization */
15155 #define WHERE_GROUPBY 0x0040 /* pOrderBy is really a GROUP BY */
15156 #define WHERE_DISTINCTBY 0x0080 /* pOrderby is really a DISTINCT clause */
15157 #define WHERE_WANT_DISTINCT 0x0100 /* All output needs to be distinct */
15158 #define WHERE_SORTBYGROUP 0x0200 /* Support sqlite3WhereIsSorted() */
15159 #define WHERE_SEEK_TABLE 0x0400 /* Do not defer seeks on main table */
15160 #define WHERE_ORDERBY_LIMIT 0x0800 /* ORDERBY+LIMIT on the inner loop */
15161  /* 0x1000 not currently used */
15162  /* 0x2000 not currently used */
15163 #define WHERE_USE_LIMIT 0x4000 /* Use the LIMIT in cost estimates */
15164  /* 0x8000 not currently used */
15165 
15166 /* Allowed return values from sqlite3WhereIsDistinct()
15167 */
15168 #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
15169 #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
15170 #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
15171 #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
15172 
15173 /*
15174 ** A NameContext defines a context in which to resolve table and column
15175 ** names. The context consists of a list of tables (the pSrcList) field and
15176 ** a list of named expression (pEList). The named expression list may
15177 ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
15178 ** to the table being operated on by INSERT, UPDATE, or DELETE. The
15179 ** pEList corresponds to the result set of a SELECT and is NULL for
15180 ** other statements.
15181 **
15182 ** NameContexts can be nested. When resolving names, the inner-most
15183 ** context is searched first. If no match is found, the next outer
15184 ** context is checked. If there is still no match, the next context
15185 ** is checked. This process continues until either a match is found
15186 ** or all contexts are check. When a match is found, the nRef member of
15187 ** the context containing the match is incremented.
15188 **
15189 ** Each subquery gets a new NameContext. The pNext field points to the
15190 ** NameContext in the parent query. Thus the process of scanning the
15191 ** NameContext list corresponds to searching through successively outer
15192 ** subqueries looking for a match.
15193 */
15194 struct NameContext {
15195  Parse *pParse; /* The parser */
15196  SrcList *pSrcList; /* One or more tables used to resolve names */
15197  ExprList *pEList; /* Optional list of result-set columns */
15198  AggInfo *pAggInfo; /* Information about aggregates at this level */
15199  NameContext *pNext; /* Next outer name context. NULL for outermost */
15200  int nRef; /* Number of names resolved by this context */
15201  int nErr; /* Number of errors encountered while resolving names */
15202  u16 ncFlags; /* Zero or more NC_* flags defined below */
15203 };
15204 
15205 /*
15206 ** Allowed values for the NameContext, ncFlags field.
15207 **
15208 ** Value constraints (all checked via assert()):
15209 ** NC_HasAgg == SF_HasAgg
15210 ** NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
15211 **
15212 */
15213 #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
15214 #define NC_PartIdx 0x0002 /* True if resolving a partial index WHERE */
15215 #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
15216 #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
15217 #define NC_HasAgg 0x0010 /* One or more aggregate functions seen */
15218 #define NC_IdxExpr 0x0020 /* True if resolving columns of CREATE INDEX */
15219 #define NC_VarSelect 0x0040 /* A correlated subquery has been seen */
15220 #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
15221 
15222 /*
15223 ** An instance of the following structure contains all information
15224 ** needed to generate code for a single SELECT statement.
15225 **
15226 ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
15227 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
15228 ** limit and nOffset to the value of the offset (or 0 if there is not
15229 ** offset). But later on, nLimit and nOffset become the memory locations
15230 ** in the VDBE that record the limit and offset counters.
15231 **
15232 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
15233 ** These addresses must be stored so that we can go back and fill in
15234 ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
15235 ** the number of columns in P2 can be computed at the same time
15236 ** as the OP_OpenEphm instruction is coded because not
15237 ** enough information about the compound query is known at that point.
15238 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
15239 ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
15240 ** sequences for the ORDER BY clause.
15241 */
15242 struct Select {
15243  ExprList *pEList; /* The fields of the result */
15244  u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
15245  LogEst nSelectRow; /* Estimated number of result rows */
15246  u32 selFlags; /* Various SF_* values */
15247  int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
15248 #if SELECTTRACE_ENABLED
15249  char zSelName[12]; /* Symbolic name of this SELECT use for debugging */
15250 #endif
15251  int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
15252  SrcList *pSrc; /* The FROM clause */
15253  Expr *pWhere; /* The WHERE clause */
15254  ExprList *pGroupBy; /* The GROUP BY clause */
15255  Expr *pHaving; /* The HAVING clause */
15256  ExprList *pOrderBy; /* The ORDER BY clause */
15257  Select *pPrior; /* Prior select in a compound select statement */
15258  Select *pNext; /* Next select to the left in a compound */
15259  Expr *pLimit; /* LIMIT expression. NULL means not used. */
15260  Expr *pOffset; /* OFFSET expression. NULL means not used. */
15261  With *pWith; /* WITH clause attached to this select. Or NULL. */
15262 };
15263 
15264 /*
15265 ** Allowed values for Select.selFlags. The "SF" prefix stands for
15266 ** "Select Flag".
15267 **
15268 ** Value constraints (all checked via assert())
15269 ** SF_HasAgg == NC_HasAgg
15270 ** SF_MinMaxAgg == NC_MinMaxAgg == SQLITE_FUNC_MINMAX
15271 ** SF_FixedLimit == WHERE_USE_LIMIT
15272 */
15273 #define SF_Distinct 0x00001 /* Output should be DISTINCT */
15274 #define SF_All 0x00002 /* Includes the ALL keyword */
15275 #define SF_Resolved 0x00004 /* Identifiers have been resolved */
15276 #define SF_Aggregate 0x00008 /* Contains agg functions or a GROUP BY */
15277 #define SF_HasAgg 0x00010 /* Contains aggregate functions */
15278 #define SF_UsesEphemeral 0x00020 /* Uses the OpenEphemeral opcode */
15279 #define SF_Expanded 0x00040 /* sqlite3SelectExpand() called on this */
15280 #define SF_HasTypeInfo 0x00080 /* FROM subqueries have Table metadata */
15281 #define SF_Compound 0x00100 /* Part of a compound query */
15282 #define SF_Values 0x00200 /* Synthesized from VALUES clause */
15283 #define SF_MultiValue 0x00400 /* Single VALUES term with multiple rows */
15284 #define SF_NestedFrom 0x00800 /* Part of a parenthesized FROM clause */
15285 #define SF_MinMaxAgg 0x01000 /* Aggregate containing min() or max() */
15286 #define SF_Recursive 0x02000 /* The recursive part of a recursive CTE */
15287 #define SF_FixedLimit 0x04000 /* nSelectRow set by a constant LIMIT */
15288 #define SF_MaybeConvert 0x08000 /* Need convertCompoundSelectToSubquery() */
15289 #define SF_Converted 0x10000 /* By convertCompoundSelectToSubquery() */
15290 #define SF_IncludeHidden 0x20000 /* Include hidden columns in output */
15291 
15292 
15293 /*
15294 ** The results of a SELECT can be distributed in several ways, as defined
15295 ** by one of the following macros. The "SRT" prefix means "SELECT Result
15296 ** Type".
15297 **
15298 ** SRT_Union Store results as a key in a temporary index
15299 ** identified by pDest->iSDParm.
15300 **
15301 ** SRT_Except Remove results from the temporary index pDest->iSDParm.
15302 **
15303 ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
15304 ** set is not empty.
15305 **
15306 ** SRT_Discard Throw the results away. This is used by SELECT
15307 ** statements within triggers whose only purpose is
15308 ** the side-effects of functions.
15309 **
15310 ** All of the above are free to ignore their ORDER BY clause. Those that
15311 ** follow must honor the ORDER BY clause.
15312 **
15313 ** SRT_Output Generate a row of output (using the OP_ResultRow
15314 ** opcode) for each row in the result set.
15315 **
15316 ** SRT_Mem Only valid if the result is a single column.
15317 ** Store the first column of the first result row
15318 ** in register pDest->iSDParm then abandon the rest
15319 ** of the query. This destination implies "LIMIT 1".
15320 **
15321 ** SRT_Set The result must be a single column. Store each
15322 ** row of result as the key in table pDest->iSDParm.
15323 ** Apply the affinity pDest->affSdst before storing
15324 ** results. Used to implement "IN (SELECT ...)".
15325 **
15326 ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
15327 ** the result there. The cursor is left open after
15328 ** returning. This is like SRT_Table except that
15329 ** this destination uses OP_OpenEphemeral to create
15330 ** the table first.
15331 **
15332 ** SRT_Coroutine Generate a co-routine that returns a new row of
15333 ** results each time it is invoked. The entry point
15334 ** of the co-routine is stored in register pDest->iSDParm
15335 ** and the result row is stored in pDest->nDest registers
15336 ** starting with pDest->iSdst.
15337 **
15338 ** SRT_Table Store results in temporary table pDest->iSDParm.
15339 ** SRT_Fifo This is like SRT_EphemTab except that the table
15340 ** is assumed to already be open. SRT_Fifo has
15341 ** the additional property of being able to ignore
15342 ** the ORDER BY clause.
15343 **
15344 ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
15345 ** But also use temporary table pDest->iSDParm+1 as
15346 ** a record of all prior results and ignore any duplicate
15347 ** rows. Name means: "Distinct Fifo".
15348 **
15349 ** SRT_Queue Store results in priority queue pDest->iSDParm (really
15350 ** an index). Append a sequence number so that all entries
15351 ** are distinct.
15352 **
15353 ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
15354 ** the same record has never been stored before. The
15355 ** index at pDest->iSDParm+1 hold all prior stores.
15356 */
15357 #define SRT_Union 1 /* Store result as keys in an index */
15358 #define SRT_Except 2 /* Remove result from a UNION index */
15359 #define SRT_Exists 3 /* Store 1 if the result is not empty */
15360 #define SRT_Discard 4 /* Do not save the results anywhere */
15361 #define SRT_Fifo 5 /* Store result as data with an automatic rowid */
15362 #define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */
15363 #define SRT_Queue 7 /* Store result in an queue */
15364 #define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */
15365 
15366 /* The ORDER BY clause is ignored for all of the above */
15367 #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
15368 
15369 #define SRT_Output 9 /* Output each row of result */
15370 #define SRT_Mem 10 /* Store result in a memory cell */
15371 #define SRT_Set 11 /* Store results as keys in an index */
15372 #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
15373 #define SRT_Coroutine 13 /* Generate a single row of result */
15374 #define SRT_Table 14 /* Store result as data with an automatic rowid */
15375 
15376 /*
15377 ** An instance of this object describes where to put of the results of
15378 ** a SELECT statement.
15379 */
15380 struct SelectDest {
15381  u8 eDest; /* How to dispose of the results. On of SRT_* above. */
15382  char affSdst; /* Affinity used when eDest==SRT_Set */
15383  int iSDParm; /* A parameter used by the eDest disposal method */
15384  int iSdst; /* Base register where results are written */
15385  int nSdst; /* Number of registers allocated */
15386  ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
15387 };
15388 
15389 /*
15390 ** During code generation of statements that do inserts into AUTOINCREMENT
15391 ** tables, the following information is attached to the Table.u.autoInc.p
15392 ** pointer of each autoincrement table to record some side information that
15393 ** the code generator needs. We have to keep per-table autoincrement
15394 ** information in case inserts are done within triggers. Triggers do not
15395 ** normally coordinate their activities, but we do need to coordinate the
15396 ** loading and saving of autoincrement information.
15397 */
15398 struct AutoincInfo {
15399  AutoincInfo *pNext; /* Next info block in a list of them all */
15400  Table *pTab; /* Table this info block refers to */
15401  int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
15402  int regCtr; /* Memory register holding the rowid counter */
15403 };
15404 
15405 /*
15406 ** Size of the column cache
15407 */
15408 #ifndef SQLITE_N_COLCACHE
15409 # define SQLITE_N_COLCACHE 10
15410 #endif
15411 
15412 /*
15413 ** At least one instance of the following structure is created for each
15414 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
15415 ** statement. All such objects are stored in the linked list headed at
15416 ** Parse.pTriggerPrg and deleted once statement compilation has been
15417 ** completed.
15418 **
15419 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
15420 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
15421 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
15422 ** The Parse.pTriggerPrg list never contains two entries with the same
15423 ** values for both pTrigger and orconf.
15424 **
15425 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
15426 ** accessed (or set to 0 for triggers fired as a result of INSERT
15427 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
15428 ** a mask of new.* columns used by the program.
15429 */
15430 struct TriggerPrg {
15431  Trigger *pTrigger; /* Trigger this program was coded from */
15432  TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
15433  SubProgram *pProgram; /* Program implementing pTrigger/orconf */
15434  int orconf; /* Default ON CONFLICT policy */
15435  u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
15436 };
15437 
15438 /*
15439 ** The yDbMask datatype for the bitmask of all attached databases.
15440 */
15441 #if SQLITE_MAX_ATTACHED>30
15442  typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
15443 # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
15444 # define DbMaskZero(M) memset((M),0,sizeof(M))
15445 # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
15446 # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
15447 # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
15448 #else
15449  typedef unsigned int yDbMask;
15450 # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
15451 # define DbMaskZero(M) (M)=0
15452 # define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
15453 # define DbMaskAllZero(M) (M)==0
15454 # define DbMaskNonZero(M) (M)!=0
15455 #endif
15456 
15457 /*
15458 ** An SQL parser context. A copy of this structure is passed through
15459 ** the parser and down into all the parser action routine in order to
15460 ** carry around information that is global to the entire parse.
15461 **
15462 ** The structure is divided into two parts. When the parser and code
15463 ** generate call themselves recursively, the first part of the structure
15464 ** is constant but the second part is reset at the beginning and end of
15465 ** each recursion.
15466 **
15467 ** The nTableLock and aTableLock variables are only used if the shared-cache
15468 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
15469 ** used to store the set of table-locks required by the statement being
15470 ** compiled. Function sqlite3TableLock() is used to add entries to the
15471 ** list.
15472 */
15473 struct Parse {
15474  sqlite3 *db; /* The main database structure */
15475  char *zErrMsg; /* An error message */
15476  Vdbe *pVdbe; /* An engine for executing database bytecode */
15477  int rc; /* Return code from execution */
15478  u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
15479  u8 checkSchema; /* Causes schema cookie check after an error */
15480  u8 nested; /* Number of nested calls to the parser/code generator */
15481  u8 nTempReg; /* Number of temporary registers in aTempReg[] */
15482  u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
15483  u8 mayAbort; /* True if statement may throw an ABORT exception */
15484  u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
15485  u8 okConstFactor; /* OK to factor out constants */
15486  u8 disableLookaside; /* Number of times lookaside has been disabled */
15487  u8 nColCache; /* Number of entries in aColCache[] */
15488  int aTempReg[8]; /* Holding area for temporary registers */
15489  int nRangeReg; /* Size of the temporary register block */
15490  int iRangeReg; /* First register in temporary register block */
15491  int nErr; /* Number of errors seen */
15492  int nTab; /* Number of previously allocated VDBE cursors */
15493  int nMem; /* Number of memory cells used so far */
15494  int nSet; /* Number of sets used so far */
15495  int nOnce; /* Number of OP_Once instructions so far */
15496  int nOpAlloc; /* Number of slots allocated for Vdbe.aOp[] */
15497  int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
15498  int iFixedOp; /* Never back out opcodes iFixedOp-1 or earlier */
15499  int ckBase; /* Base register of data during check constraints */
15500  int iSelfTab; /* Table of an index whose exprs are being coded */
15501  int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
15502  int iCacheCnt; /* Counter used to generate aColCache[].lru values */
15503  int nLabel; /* Number of labels used */
15504  int *aLabel; /* Space to hold the labels */
15505  struct yColCache {
15506  int iTable; /* Table cursor number */
15507  i16 iColumn; /* Table column number */
15508  u8 tempReg; /* iReg is a temp register that needs to be freed */
15509  int iLevel; /* Nesting level */
15510  int iReg; /* Reg with value of this column. 0 means none. */
15511  int lru; /* Least recently used entry has the smallest value */
15512  } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
15513  ExprList *pConstExpr;/* Constant expressions */
15514  Token constraintName;/* Name of the constraint currently being parsed */
15515  yDbMask writeMask; /* Start a write transaction on these databases */
15516  yDbMask cookieMask; /* Bitmask of schema verified databases */
15517  int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
15518  int regRowid; /* Register holding rowid of CREATE TABLE entry */
15519  int regRoot; /* Register holding root page number for new objects */
15520  int nMaxArg; /* Max args passed to user function by sub-program */
15521 #if SELECTTRACE_ENABLED
15522  int nSelect; /* Number of SELECT statements seen */
15523  int nSelectIndent; /* How far to indent SELECTTRACE() output */
15524 #endif
15525 #ifndef SQLITE_OMIT_SHARED_CACHE
15526  int nTableLock; /* Number of locks in aTableLock */
15527  TableLock *aTableLock; /* Required table locks for shared-cache mode */
15528 #endif
15529  AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
15530 
15531  /* Information used while coding trigger programs. */
15532  Parse *pToplevel; /* Parse structure for main program (or NULL) */
15533  Table *pTriggerTab; /* Table triggers are being coded for */
15534  int addrCrTab; /* Address of OP_CreateTable opcode on CREATE TABLE */
15535  u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
15536  u32 oldmask; /* Mask of old.* columns referenced */
15537  u32 newmask; /* Mask of new.* columns referenced */
15538  u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
15539  u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
15540  u8 disableTriggers; /* True to disable triggers */
15541 
15542  /************************************************************************
15543  ** Above is constant between recursions. Below is reset before and after
15544  ** each recursion. The boundary between these two regions is determined
15545  ** using offsetof(Parse,nVar) so the nVar field must be the first field
15546  ** in the recursive region.
15547  ************************************************************************/
15548 
15549  ynVar nVar; /* Number of '?' variables seen in the SQL so far */
15550  int nzVar; /* Number of available slots in azVar[] */
15551  u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
15552  u8 explain; /* True if the EXPLAIN flag is found on the query */
15553 #ifndef SQLITE_OMIT_VIRTUALTABLE
15554  u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
15555  int nVtabLock; /* Number of virtual tables to lock */
15556 #endif
15557  int nAlias; /* Number of aliased result set columns */
15558  int nHeight; /* Expression tree height of current sub-select */
15559 #ifndef SQLITE_OMIT_EXPLAIN
15560  int iSelectId; /* ID of current select for EXPLAIN output */
15561  int iNextSelectId; /* Next available select ID for EXPLAIN output */
15562 #endif
15563  char **azVar; /* Pointers to names of parameters */
15564  Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
15565  const char *zTail; /* All SQL text past the last semicolon parsed */
15566  Table *pNewTable; /* A table being constructed by CREATE TABLE */
15567  Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
15568  const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
15569  Token sNameToken; /* Token with unqualified schema object name */
15570  Token sLastToken; /* The last token parsed */
15571 #ifndef SQLITE_OMIT_VIRTUALTABLE
15572  Token sArg; /* Complete text of a module argument */
15573  Table **apVtabLock; /* Pointer to virtual tables needing locking */
15574 #endif
15575  Table *pZombieTab; /* List of Table objects to delete after code gen */
15576  TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
15577  With *pWith; /* Current WITH clause, or NULL */
15578  With *pWithToFree; /* Free this WITH object at the end of the parse */
15579 };
15580 
15581 /*
15582 ** Return true if currently inside an sqlite3_declare_vtab() call.
15583 */
15584 #ifdef SQLITE_OMIT_VIRTUALTABLE
15585  #define IN_DECLARE_VTAB 0
15586 #else
15587  #define IN_DECLARE_VTAB (pParse->declareVtab)
15588 #endif
15589 
15590 /*
15591 ** An instance of the following structure can be declared on a stack and used
15592 ** to save the Parse.zAuthContext value so that it can be restored later.
15593 */
15594 struct AuthContext {
15595  const char *zAuthContext; /* Put saved Parse.zAuthContext here */
15596  Parse *pParse; /* The Parse structure */
15597 };
15598 
15599 /*
15600 ** Bitfield flags for P5 value in various opcodes.
15601 **
15602 ** Value constraints (enforced via assert()):
15603 ** OPFLAG_LENGTHARG == SQLITE_FUNC_LENGTH
15604 ** OPFLAG_TYPEOFARG == SQLITE_FUNC_TYPEOF
15605 ** OPFLAG_BULKCSR == BTREE_BULKLOAD
15606 ** OPFLAG_SEEKEQ == BTREE_SEEK_EQ
15607 ** OPFLAG_FORDELETE == BTREE_FORDELETE
15608 ** OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
15609 ** OPFLAG_AUXDELETE == BTREE_AUXDELETE
15610 */
15611 #define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */
15612  /* Also used in P2 (not P5) of OP_Delete */
15613 #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
15614 #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
15615 #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
15616 #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
15617 #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
15618 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
15619 #define OPFLAG_ISNOOP 0x40 /* OP_Delete does pre-update-hook only */
15620 #endif
15621 #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
15622 #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
15623 #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
15624 #define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
15625 #define OPFLAG_FORDELETE 0x08 /* OP_Open should use BTREE_FORDELETE */
15626 #define OPFLAG_P2ISREG 0x10 /* P2 to OP_Open** is a register number */
15627 #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
15628 #define OPFLAG_SAVEPOSITION 0x02 /* OP_Delete: keep cursor position */
15629 #define OPFLAG_AUXDELETE 0x04 /* OP_Delete: index in a DELETE op */
15630 
15631 /*
15632  * Each trigger present in the database schema is stored as an instance of
15633  * struct Trigger.
15634  *
15635  * Pointers to instances of struct Trigger are stored in two ways.
15636  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
15637  * database). This allows Trigger structures to be retrieved by name.
15638  * 2. All triggers associated with a single table form a linked list, using the
15639  * pNext member of struct Trigger. A pointer to the first element of the
15640  * linked list is stored as the "pTrigger" member of the associated
15641  * struct Table.
15642  *
15643  * The "step_list" member points to the first element of a linked list
15644  * containing the SQL statements specified as the trigger program.
15645  */
15646 struct Trigger {
15647  char *zName; /* The name of the trigger */
15648  char *table; /* The table or view to which the trigger applies */
15649  u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
15650  u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
15651  Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
15652  IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
15653  the <column-list> is stored here */
15654  Schema *pSchema; /* Schema containing the trigger */
15655  Schema *pTabSchema; /* Schema containing the table */
15656  TriggerStep *step_list; /* Link list of trigger program steps */
15657  Trigger *pNext; /* Next trigger associated with the table */
15658 };
15659 
15660 /*
15661 ** A trigger is either a BEFORE or an AFTER trigger. The following constants
15662 ** determine which.
15663 **
15664 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
15665 ** In that cases, the constants below can be ORed together.
15666 */
15667 #define TRIGGER_BEFORE 1
15668 #define TRIGGER_AFTER 2
15669 
15670 /*
15671  * An instance of struct TriggerStep is used to store a single SQL statement
15672  * that is a part of a trigger-program.
15673  *
15674  * Instances of struct TriggerStep are stored in a singly linked list (linked
15675  * using the "pNext" member) referenced by the "step_list" member of the
15676  * associated struct Trigger instance. The first element of the linked list is
15677  * the first step of the trigger-program.
15678  *
15679  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
15680  * "SELECT" statement. The meanings of the other members is determined by the
15681  * value of "op" as follows:
15682  *
15683  * (op == TK_INSERT)
15684  * orconf -> stores the ON CONFLICT algorithm
15685  * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
15686  * this stores a pointer to the SELECT statement. Otherwise NULL.
15687  * zTarget -> Dequoted name of the table to insert into.
15688  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
15689  * this stores values to be inserted. Otherwise NULL.
15690  * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
15691  * statement, then this stores the column-names to be
15692  * inserted into.
15693  *
15694  * (op == TK_DELETE)
15695  * zTarget -> Dequoted name of the table to delete from.
15696  * pWhere -> The WHERE clause of the DELETE statement if one is specified.
15697  * Otherwise NULL.
15698  *
15699  * (op == TK_UPDATE)
15700  * zTarget -> Dequoted name of the table to update.
15701  * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
15702  * Otherwise NULL.
15703  * pExprList -> A list of the columns to update and the expressions to update
15704  * them to. See sqlite3Update() documentation of "pChanges"
15705  * argument.
15706  *
15707  */
15708 struct TriggerStep {
15709  u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
15710  u8 orconf; /* OE_Rollback etc. */
15711  Trigger *pTrig; /* The trigger that this step is a part of */
15712  Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */
15713  char *zTarget; /* Target table for DELETE, UPDATE, INSERT */
15714  Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
15715  ExprList *pExprList; /* SET clause for UPDATE. */
15716  IdList *pIdList; /* Column names for INSERT */
15717  TriggerStep *pNext; /* Next in the link-list */
15718  TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
15719 };
15720 
15721 /*
15722 ** The following structure contains information used by the sqliteFix...
15723 ** routines as they walk the parse tree to make database references
15724 ** explicit.
15725 */
15726 typedef struct DbFixer DbFixer;
15727 struct DbFixer {
15728  Parse *pParse; /* The parsing context. Error messages written here */
15729  Schema *pSchema; /* Fix items to this schema */
15730  int bVarOnly; /* Check for variable references only */
15731  const char *zDb; /* Make sure all objects are contained in this database */
15732  const char *zType; /* Type of the container - used for error messages */
15733  const Token *pName; /* Name of the container - used for error messages */
15734 };
15735 
15736 /*
15737 ** An objected used to accumulate the text of a string where we
15738 ** do not necessarily know how big the string will be in the end.
15739 */
15740 struct StrAccum {
15741  sqlite3 *db; /* Optional database for lookaside. Can be NULL */
15742  char *zBase; /* A base allocation. Not from malloc. */
15743  char *zText; /* The string collected so far */
15744  u32 nChar; /* Length of the string so far */
15745  u32 nAlloc; /* Amount of space allocated in zText */
15746  u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */
15747  u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
15748  u8 printfFlags; /* SQLITE_PRINTF flags below */
15749 };
15750 #define STRACCUM_NOMEM 1
15751 #define STRACCUM_TOOBIG 2
15752 #define SQLITE_PRINTF_INTERNAL 0x01 /* Internal-use-only converters allowed */
15753 #define SQLITE_PRINTF_SQLFUNC 0x02 /* SQL function arguments to VXPrintf */
15754 #define SQLITE_PRINTF_MALLOCED 0x04 /* True if xText is allocated space */
15755 
15756 #define isMalloced(X) (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
15757 
15758 
15759 /*
15760 ** A pointer to this structure is used to communicate information
15761 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
15762 */
15763 typedef struct {
15764  sqlite3 *db; /* The database being initialized */
15765  char **pzErrMsg; /* Error message stored here */
15766  int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
15767  int rc; /* Result code stored here */
15768 } InitData;
15769 
15770 /*
15771 ** Structure containing global configuration data for the SQLite library.
15772 **
15773 ** This structure also contains some state information.
15774 */
15776  int bMemstat; /* True to enable memory status */
15777  int bCoreMutex; /* True to enable core mutexing */
15778  int bFullMutex; /* True to enable full mutexing */
15779  int bOpenUri; /* True to interpret filenames as URIs */
15780  int bUseCis; /* Use covering indices for full-scans */
15781  int mxStrlen; /* Maximum string length */
15782  int neverCorrupt; /* Database is always well-formed */
15783  int szLookaside; /* Default lookaside buffer size */
15784  int nLookaside; /* Default lookaside buffer count */
15785  int nStmtSpill; /* Stmt-journal spill-to-disk threshold */
15786  sqlite3_mem_methods m; /* Low-level memory allocation interface */
15787  sqlite3_mutex_methods mutex; /* Low-level mutex interface */
15788  sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
15789  void *pHeap; /* Heap storage space */
15790  int nHeap; /* Size of pHeap[] */
15791  int mnReq, mxReq; /* Min and max heap requests sizes */
15792  sqlite3_int64 szMmap; /* mmap() space per open file */
15793  sqlite3_int64 mxMmap; /* Maximum value for szMmap */
15794  void *pScratch; /* Scratch memory */
15795  int szScratch; /* Size of each scratch buffer */
15796  int nScratch; /* Number of scratch buffers */
15797  void *pPage; /* Page cache memory */
15798  int szPage; /* Size of each page in pPage[] */
15799  int nPage; /* Number of pages in pPage[] */
15800  int mxParserStack; /* maximum depth of the parser stack */
15801  int sharedCacheEnabled; /* true if shared-cache mode enabled */
15802  u32 szPma; /* Maximum Sorter PMA size */
15803  /* The above might be initialized to non-zero. The following need to always
15804  ** initially be zero, however. */
15805  int isInit; /* True after initialization has finished */
15806  int inProgress; /* True while initialization in progress */
15807  int isMutexInit; /* True after mutexes are initialized */
15808  int isMallocInit; /* True after malloc is initialized */
15809  int isPCacheInit; /* True after malloc is initialized */
15810  int nRefInitMutex; /* Number of users of pInitMutex */
15811  sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
15812  void (*xLog)(void*,int,const char*); /* Function for logging */
15813  void *pLogArg; /* First argument to xLog() */
15814 #ifdef SQLITE_ENABLE_SQLLOG
15815  void(*xSqllog)(void*,sqlite3*,const char*, int);
15816  void *pSqllogArg;
15817 #endif
15818 #ifdef SQLITE_VDBE_COVERAGE
15819  /* The following callback (if not NULL) is invoked on every VDBE branch
15820  ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
15821  */
15822  void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx); /* Callback */
15823  void *pVdbeBranchArg; /* 1st argument */
15824 #endif
15825 #ifndef SQLITE_OMIT_BUILTIN_TEST
15826  int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
15827 #endif
15828  int bLocaltimeFault; /* True to fail localtime() calls */
15829 };
15830 
15831 /*
15832 ** This macro is used inside of assert() statements to indicate that
15833 ** the assert is only valid on a well-formed database. Instead of:
15834 **
15835 ** assert( X );
15836 **
15837 ** One writes:
15838 **
15839 ** assert( X || CORRUPT_DB );
15840 **
15841 ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
15842 ** that the database is definitely corrupt, only that it might be corrupt.
15843 ** For most test cases, CORRUPT_DB is set to false using a special
15844 ** sqlite3_test_control(). This enables assert() statements to prove
15845 ** things that are always true for well-formed databases.
15846 */
15847 #define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
15848 
15849 /*
15850 ** Context pointer passed down through the tree-walk.
15851 */
15852 struct Walker {
15853  Parse *pParse; /* Parser context. */
15854  int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
15855  int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
15856  void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
15857  int walkerDepth; /* Number of subqueries */
15858  u8 eCode; /* A small processing code */
15859  union { /* Extra data for callback */
15860  NameContext *pNC; /* Naming context */
15861  int n; /* A counter */
15862  int iCur; /* A cursor number */
15863  SrcList *pSrcList; /* FROM clause */
15864  struct SrcCount *pSrcCount; /* Counting column references */
15865  struct CCurHint *pCCurHint; /* Used by codeCursorHint() */
15866  int *aiCol; /* array of column indexes */
15867  struct IdxCover *pIdxCover; /* Check for index coverage */
15868  } u;
15869 };
15870 
15871 /* Forward declarations */
15872 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
15873 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
15874 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
15875 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
15876 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
15877 SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
15878 
15879 /*
15880 ** Return code from the parse-tree walking primitives and their
15881 ** callbacks.
15882 */
15883 #define WRC_Continue 0 /* Continue down into children */
15884 #define WRC_Prune 1 /* Omit children but continue walking siblings */
15885 #define WRC_Abort 2 /* Abandon the tree walk */
15886 
15887 /*
15888 ** An instance of this structure represents a set of one or more CTEs
15889 ** (common table expressions) created by a single WITH clause.
15890 */
15891 struct With {
15892  int nCte; /* Number of CTEs in the WITH clause */
15893  With *pOuter; /* Containing WITH clause, or NULL */
15894  struct Cte { /* For each CTE in the WITH clause.... */
15895  char *zName; /* Name of this CTE */
15896  ExprList *pCols; /* List of explicit column names, or NULL */
15897  Select *pSelect; /* The definition of this CTE */
15898  const char *zCteErr; /* Error message for circular references */
15899  } a[1];
15900 };
15901 
15902 #ifdef SQLITE_DEBUG
15903 /*
15904 ** An instance of the TreeView object is used for printing the content of
15905 ** data structures on sqlite3DebugPrintf() using a tree-like view.
15906 */
15907 struct TreeView {
15908  int iLevel; /* Which level of the tree we are on */
15909  u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
15910 };
15911 #endif /* SQLITE_DEBUG */
15912 
15913 /*
15914 ** Assuming zIn points to the first byte of a UTF-8 character,
15915 ** advance zIn to point to the first byte of the next UTF-8 character.
15916 */
15917 #define SQLITE_SKIP_UTF8(zIn) { \
15918  if( (*(zIn++))>=0xc0 ){ \
15919  while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
15920  } \
15921 }
15922 
15923 /*
15924 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
15925 ** the same name but without the _BKPT suffix. These macros invoke
15926 ** routines that report the line-number on which the error originated
15927 ** using sqlite3_log(). The routines also provide a convenient place
15928 ** to set a debugger breakpoint.
15929 */
15930 SQLITE_PRIVATE int sqlite3CorruptError(int);
15931 SQLITE_PRIVATE int sqlite3MisuseError(int);
15932 SQLITE_PRIVATE int sqlite3CantopenError(int);
15933 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
15934 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
15935 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
15936 #ifdef SQLITE_DEBUG
15937 SQLITE_PRIVATE int sqlite3NomemError(int);
15938 SQLITE_PRIVATE int sqlite3IoerrnomemError(int);
15939 # define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
15940 # define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
15941 #else
15942 # define SQLITE_NOMEM_BKPT SQLITE_NOMEM
15943 # define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
15944 #endif
15945 
15946 /*
15947 ** FTS3 and FTS4 both require virtual table support
15948 */
15949 #if defined(SQLITE_OMIT_VIRTUALTABLE)
15950 # undef SQLITE_ENABLE_FTS3
15951 # undef SQLITE_ENABLE_FTS4
15952 #endif
15953 
15954 /*
15955 ** FTS4 is really an extension for FTS3. It is enabled using the
15956 ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
15957 ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
15958 */
15959 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
15960 # define SQLITE_ENABLE_FTS3 1
15961 #endif
15962 
15963 /*
15964 ** The ctype.h header is needed for non-ASCII systems. It is also
15965 ** needed by FTS3 when FTS3 is included in the amalgamation.
15966 */
15967 #if !defined(SQLITE_ASCII) || \
15968  (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
15969 # include <ctype.h>
15970 #endif
15971 
15972 /*
15973 ** The following macros mimic the standard library functions toupper(),
15974 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
15975 ** sqlite versions only work for ASCII characters, regardless of locale.
15976 */
15977 #ifdef SQLITE_ASCII
15978 # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
15979 # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
15980 # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
15981 # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
15982 # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
15983 # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
15984 # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
15985 # define sqlite3Isquote(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
15986 #else
15987 # define sqlite3Toupper(x) toupper((unsigned char)(x))
15988 # define sqlite3Isspace(x) isspace((unsigned char)(x))
15989 # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
15990 # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
15991 # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
15992 # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
15993 # define sqlite3Tolower(x) tolower((unsigned char)(x))
15994 # define sqlite3Isquote(x) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
15995 #endif
15996 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
15997 SQLITE_PRIVATE int sqlite3IsIdChar(u8);
15998 #endif
15999 
16000 /*
16001 ** Internal function prototypes
16002 */
16003 SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
16004 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
16005 SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);
16006 #define sqlite3StrNICmp sqlite3_strnicmp
16007 
16008 SQLITE_PRIVATE int sqlite3MallocInit(void);
16009 SQLITE_PRIVATE void sqlite3MallocEnd(void);
16010 SQLITE_PRIVATE void *sqlite3Malloc(u64);
16011 SQLITE_PRIVATE void *sqlite3MallocZero(u64);
16012 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
16013 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
16014 SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64);
16015 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
16016 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
16017 SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
16018 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
16019 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
16020 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
16021 SQLITE_PRIVATE int sqlite3MallocSize(void*);
16022 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
16023 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
16024 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
16025 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
16026 SQLITE_PRIVATE void sqlite3PageFree(void*);
16027 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
16028 #ifndef SQLITE_OMIT_BUILTIN_TEST
16029 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
16030 #endif
16031 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
16032 
16033 /*
16034 ** On systems with ample stack space and that support alloca(), make
16035 ** use of alloca() to obtain space for large automatic objects. By default,
16036 ** obtain space from malloc().
16037 **
16038 ** The alloca() routine never returns NULL. This will cause code paths
16039 ** that deal with sqlite3StackAlloc() failures to be unreachable.
16040 */
16041 #ifdef SQLITE_USE_ALLOCA
16042 # define sqlite3StackAllocRaw(D,N) alloca(N)
16043 # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
16044 # define sqlite3StackFree(D,P)
16045 #else
16046 # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
16047 # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
16048 # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
16049 #endif
16050 
16051 /* Do not allow both MEMSYS5 and MEMSYS3 to be defined together. If they
16052 ** are, disable MEMSYS3
16053 */
16054 #ifdef SQLITE_ENABLE_MEMSYS5
16055 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
16056 #undef SQLITE_ENABLE_MEMSYS3
16057 #endif
16058 #ifdef SQLITE_ENABLE_MEMSYS3
16059 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
16060 #endif
16061 
16062 
16063 #ifndef SQLITE_MUTEX_OMIT
16064 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
16065 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
16066 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
16067 SQLITE_PRIVATE int sqlite3MutexInit(void);
16068 SQLITE_PRIVATE int sqlite3MutexEnd(void);
16069 #endif
16070 #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
16071 SQLITE_PRIVATE void sqlite3MemoryBarrier(void);
16072 #else
16073 # define sqlite3MemoryBarrier()
16074 #endif
16075 
16076 SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
16077 SQLITE_PRIVATE void sqlite3StatusUp(int, int);
16078 SQLITE_PRIVATE void sqlite3StatusDown(int, int);
16079 SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
16080 
16081 /* Access to mutexes used by sqlite3_status() */
16082 SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
16083 SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
16084 
16085 #ifndef SQLITE_OMIT_FLOATING_POINT
16086 SQLITE_PRIVATE int sqlite3IsNaN(double);
16087 #else
16088 # define sqlite3IsNaN(X) 0
16089 #endif
16090 
16091 /*
16092 ** An instance of the following structure holds information about SQL
16093 ** functions arguments that are the parameters to the printf() function.
16094 */
16095 struct PrintfArguments {
16096  int nArg; /* Total number of arguments */
16097  int nUsed; /* Number of arguments used so far */
16098  sqlite3_value **apArg; /* The argument values */
16099 };
16100 
16101 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, const char*, va_list);
16102 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
16103 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
16104 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
16105 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
16106 SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
16107 #endif
16108 #if defined(SQLITE_TEST)
16109 SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
16110 #endif
16111 
16112 #if defined(SQLITE_DEBUG)
16113 SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
16114 SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
16115 SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
16116 SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView*, const With*, u8);
16117 #endif
16118 
16119 
16120 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
16121 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
16122 SQLITE_PRIVATE void sqlite3Dequote(char*);
16123 SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
16124 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
16125 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
16126 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
16127 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
16128 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
16129 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
16130 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
16131 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
16132 #ifdef SQLITE_DEBUG
16133 SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
16134 #endif
16135 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
16136 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
16137 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
16138 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
16139 SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
16140 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
16141 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
16142 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
16143 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
16144 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
16145 SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int);
16146 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
16147 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
16148 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
16149 SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
16150 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
16151 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
16152 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
16153 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
16154 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
16155 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
16156 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
16157 SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
16158 SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
16159 SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*);
16160 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
16161 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
16162 SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
16163 SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
16164 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
16165 #if SQLITE_ENABLE_HIDDEN_COLUMNS
16166 SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table*, Column*);
16167 #else
16168 # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
16169 #endif
16170 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*);
16171 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
16172 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
16173 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
16174 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
16175 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
16176 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
16177 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
16178  sqlite3_vfs**,char**,char **);
16179 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
16180 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
16181 
16182 #ifdef SQLITE_OMIT_BUILTIN_TEST
16183 # define sqlite3FaultSim(X) SQLITE_OK
16184 #else
16185 SQLITE_PRIVATE int sqlite3FaultSim(int);
16186 #endif
16187 
16188 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
16189 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
16190 SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
16191 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
16192 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
16193 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
16194 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
16195 #ifndef SQLITE_OMIT_BUILTIN_TEST
16196 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
16197 #endif
16198 
16199 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
16200 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
16201 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
16202 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
16203 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
16204 
16205 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
16206 
16207 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
16208 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
16209 #else
16210 # define sqlite3ViewGetColumnNames(A,B) 0
16211 #endif
16212 
16213 #if SQLITE_MAX_ATTACHED>30
16214 SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
16215 #endif
16216 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
16217 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
16218 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
16219 #ifndef SQLITE_OMIT_AUTOINCREMENT
16220 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
16221 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
16222 #else
16223 # define sqlite3AutoincrementBegin(X)
16224 # define sqlite3AutoincrementEnd(X)
16225 #endif
16226 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
16227 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
16228 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
16229 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
16230 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
16231 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
16232 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
16233  Token*, Select*, Expr*, IdList*);
16234 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
16235 SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
16236 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
16237 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
16238 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
16239 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
16240 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
16241 SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
16242 SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
16243  Expr*, int, int, u8);
16244 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
16245 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
16246 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
16247  Expr*,ExprList*,u32,Expr*,Expr*);
16248 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
16249 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
16250 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
16251 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
16252 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
16253 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
16254 #endif
16255 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
16256 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
16257 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
16258 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
16259 SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);
16260 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
16261 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
16262 SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo*);
16263 SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
16264 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
16265 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
16266 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
16267 #define ONEPASS_OFF 0 /* Use of ONEPASS not allowed */
16268 #define ONEPASS_SINGLE 1 /* ONEPASS valid for a single row update */
16269 #define ONEPASS_MULTI 2 /* ONEPASS is valid for multiple rows */
16270 SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
16271 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
16272 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(Parse*, Table*, int, int, int);
16273 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
16274 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
16275 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
16276 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
16277 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
16278 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
16279 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
16280 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
16281 SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
16282 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
16283 SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
16284 SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8);
16285 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
16286 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
16287 SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
16288 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
16289 #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
16290 #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
16291 #define SQLITE_ECEL_REF 0x04 /* Use ExprList.u.x.iOrderByCol */
16292 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
16293 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
16294 SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
16295 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
16296 #define LOCATE_VIEW 0x01
16297 #define LOCATE_NOERR 0x02
16298 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
16299 SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *);
16300 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
16301 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
16302 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
16303 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
16304 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
16305 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
16306 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
16307 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
16308 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
16309 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
16310 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
16311 SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
16312 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
16313 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
16314 #ifndef SQLITE_OMIT_BUILTIN_TEST
16315 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
16316 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
16317 #endif
16318 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
16319 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
16320 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
16321 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
16322 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
16323 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
16324 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
16325 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
16326 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
16327 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
16328 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
16329 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
16330 SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
16331 #ifdef SQLITE_ENABLE_CURSOR_HINTS
16332 SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
16333 #endif
16334 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
16335 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
16336 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
16337 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
16338 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
16339  Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
16340 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
16341 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
16342 SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
16343 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
16344  u8,u8,int,int*,int*);
16345 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
16346 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
16347 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
16348 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
16349 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
16350 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
16351 SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
16352 SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
16353 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
16354 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
16355 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
16356 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
16357 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
16358 #if SELECTTRACE_ENABLED
16359 SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
16360 #else
16361 # define sqlite3SelectSetName(A,B)
16362 #endif
16363 SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
16364 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
16365 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
16366 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
16367 SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
16368 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
16369 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
16370 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
16371 
16372 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
16373 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
16374 #endif
16375 
16376 #ifndef SQLITE_OMIT_TRIGGER
16377 SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
16378  Expr*,int, int);
16379 SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
16380 SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
16381 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
16382 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
16383 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
16384 SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
16385  int, int, int);
16386 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
16387  void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
16388 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
16389 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
16390 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
16391  Select*,u8);
16392 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
16393 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
16394 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
16395 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
16396 SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
16397 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
16398 # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
16399 #else
16400 # define sqlite3TriggersExist(B,C,D,E,F) 0
16401 # define sqlite3DeleteTrigger(A,B)
16402 # define sqlite3DropTriggerPtr(A,B)
16403 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
16404 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
16405 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
16406 # define sqlite3TriggerList(X, Y) 0
16407 # define sqlite3ParseToplevel(p) p
16408 # define sqlite3IsToplevel(p) 1
16409 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
16410 #endif
16411 
16412 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
16413 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
16414 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
16415 #ifndef SQLITE_OMIT_AUTHORIZATION
16416 SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
16417 SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
16418 SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
16419 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
16420 SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
16421 #else
16422 # define sqlite3AuthRead(a,b,c,d)
16423 # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
16424 # define sqlite3AuthContextPush(a,b,c)
16425 # define sqlite3AuthContextPop(a) ((void)(a))
16426 #endif
16427 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
16428 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
16429 SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
16430 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
16431 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
16432 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
16433 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
16434 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
16435 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
16436 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
16437 SQLITE_PRIVATE int sqlite3Atoi(const char*);
16438 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
16439 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
16440 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
16441 SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
16442 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
16443 #ifndef SQLITE_OMIT_VIRTUALTABLE
16444 SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
16445 #endif
16446 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
16447  defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
16448  defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
16449 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
16450 #endif
16451 
16452 /*
16453 ** Routines to read and write variable-length integers. These used to
16454 ** be defined locally, but now we use the varint routines in the util.c
16455 ** file.
16456 */
16457 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
16458 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
16459 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
16460 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
16461 
16462 /*
16463 ** The common case is for a varint to be a single byte. They following
16464 ** macros handle the common case without a procedure call, but then call
16465 ** the procedure for larger varints.
16466 */
16467 #define getVarint32(A,B) \
16468  (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
16469 #define putVarint32(A,B) \
16470  (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
16471  sqlite3PutVarint((A),(B)))
16472 #define getVarint sqlite3GetVarint
16473 #define putVarint sqlite3PutVarint
16474 
16475 
16476 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
16477 SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
16478 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
16479 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
16480 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
16481 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
16482 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
16483 SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
16484 SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
16485 SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
16486 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
16487 SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
16488 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
16489 
16490 #if defined(SQLITE_NEED_ERR_NAME)
16491 SQLITE_PRIVATE const char *sqlite3ErrName(int);
16492 #endif
16493 
16494 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
16495 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
16496 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
16497 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
16498 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
16499 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
16500 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
16501 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
16502 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
16503 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
16504 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
16505 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
16506 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
16507 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
16508 SQLITE_PRIVATE int sqlite3AbsInt32(int);
16509 #ifdef SQLITE_ENABLE_8_3_NAMES
16510 SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
16511 #else
16512 # define sqlite3FileSuffix3(X,Y)
16513 #endif
16514 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
16515 
16516 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
16517 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
16518 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
16519  void(*)(void*));
16520 SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
16521 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
16522 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
16523 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
16524 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
16525 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
16526 #ifndef SQLITE_AMALGAMATION
16527 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
16528 SQLITE_PRIVATE const char sqlite3StrBINARY[];
16529 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
16530 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
16531 SQLITE_PRIVATE const Token sqlite3IntTokens[];
16532 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
16533 SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
16534 #ifndef SQLITE_OMIT_WSD
16535 SQLITE_PRIVATE int sqlite3PendingByte;
16536 #endif
16537 #endif
16538 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
16539 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
16540 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
16541 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
16542 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
16543 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
16544 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
16545 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
16546 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
16547 SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
16548 SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
16549 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
16550 SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
16551 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
16552 SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
16553 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
16554 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
16555 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
16556 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
16557 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
16558 SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
16559 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
16560 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
16561 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
16562 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
16563 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
16564 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
16565 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
16566 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
16567 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
16568 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
16569 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
16570 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
16571 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
16572 SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
16573 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
16574 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
16575 #ifdef SQLITE_DEBUG
16576 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
16577 #endif
16578 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
16579  void (*)(sqlite3_context*,int,sqlite3_value **),
16580  void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
16581  FuncDestructor *pDestructor
16582 );
16583 SQLITE_PRIVATE void sqlite3OomFault(sqlite3*);
16584 SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
16585 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
16586 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
16587 
16588 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
16589 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
16590 SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
16591 SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
16592 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
16593 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
16594 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
16595 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
16596 
16597 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
16598 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
16599 
16600 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
16601 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
16602 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
16603 SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
16604 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
16605 SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
16606 #endif
16607 
16608 /*
16609 ** The interface to the LEMON-generated parser
16610 */
16611 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64));
16612 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
16613 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
16614 #ifdef YYTRACKMAXSTACKDEPTH
16615 SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
16616 #endif
16617 
16618 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
16619 #ifndef SQLITE_OMIT_LOAD_EXTENSION
16620 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
16621 #else
16622 # define sqlite3CloseExtensions(X)
16623 #endif
16624 
16625 #ifndef SQLITE_OMIT_SHARED_CACHE
16626 SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
16627 #else
16628  #define sqlite3TableLock(v,w,x,y,z)
16629 #endif
16630 
16631 #ifdef SQLITE_TEST
16632 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
16633 #endif
16634 
16635 #ifdef SQLITE_OMIT_VIRTUALTABLE
16636 # define sqlite3VtabClear(Y)
16637 # define sqlite3VtabSync(X,Y) SQLITE_OK
16638 # define sqlite3VtabRollback(X)
16639 # define sqlite3VtabCommit(X)
16640 # define sqlite3VtabInSync(db) 0
16641 # define sqlite3VtabLock(X)
16642 # define sqlite3VtabUnlock(X)
16643 # define sqlite3VtabUnlockList(X)
16644 # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
16645 # define sqlite3GetVTable(X,Y) ((VTable*)0)
16646 #else
16647 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
16648 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
16649 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
16650 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
16651 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
16652 SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
16653 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
16654 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
16655 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
16656 SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
16657 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
16658 # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
16659 #endif
16660 SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
16661 SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
16662 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
16663 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
16664 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
16665 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
16666 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
16667 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
16668 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
16669 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
16670 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
16671 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
16672 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
16673 SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
16674 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
16675 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
16676 SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
16677 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
16678 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
16679 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
16680 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
16681 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
16682 #ifndef SQLITE_OMIT_WAL
16683 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
16684 SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
16685 #endif
16686 #ifndef SQLITE_OMIT_CTE
16687 SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
16688 SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
16689 SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8);
16690 #else
16691 #define sqlite3WithPush(x,y,z)
16692 #define sqlite3WithDelete(x,y)
16693 #endif
16694 
16695 /* Declarations for functions in fkey.c. All of these are replaced by
16696 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
16697 ** key functionality is available. If OMIT_TRIGGER is defined but
16698 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
16699 ** this case foreign keys are parsed, but no other functionality is
16700 ** provided (enforcement of FK constraints requires the triggers sub-system).
16701 */
16702 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
16703 SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
16704 SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
16705 SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
16706 SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
16707 SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
16708 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
16709 #else
16710  #define sqlite3FkActions(a,b,c,d,e,f)
16711  #define sqlite3FkCheck(a,b,c,d,e,f)
16712  #define sqlite3FkDropTable(a,b,c)
16713  #define sqlite3FkOldmask(a,b) 0
16714  #define sqlite3FkRequired(a,b,c,d) 0
16715 #endif
16716 #ifndef SQLITE_OMIT_FOREIGN_KEY
16717 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
16718 SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
16719 #else
16720  #define sqlite3FkDelete(a,b)
16721  #define sqlite3FkLocateIndex(a,b,c,d,e)
16722 #endif
16723 
16724 
16725 /*
16726 ** Available fault injectors. Should be numbered beginning with 0.
16727 */
16728 #define SQLITE_FAULTINJECTOR_MALLOC 0
16729 #define SQLITE_FAULTINJECTOR_COUNT 1
16730 
16731 /*
16732 ** The interface to the code in fault.c used for identifying "benign"
16733 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
16734 ** is not defined.
16735 */
16736 #ifndef SQLITE_OMIT_BUILTIN_TEST
16737 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
16738 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
16739 #else
16740  #define sqlite3BeginBenignMalloc()
16741  #define sqlite3EndBenignMalloc()
16742 #endif
16743 
16744 /*
16745 ** Allowed return values from sqlite3FindInIndex()
16746 */
16747 #define IN_INDEX_ROWID 1 /* Search the rowid of the table */
16748 #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
16749 #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
16750 #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
16751 #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
16752 /*
16753 ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
16754 */
16755 #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
16756 #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
16757 #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
16758 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*);
16759 
16760 SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
16761 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
16762 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
16763 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
16764 #endif
16765 
16766 SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
16767 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
16768 
16769 SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
16770 #if SQLITE_MAX_EXPR_DEPTH>0
16771 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
16772 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
16773 #else
16774  #define sqlite3SelectExprHeight(x) 0
16775  #define sqlite3ExprCheckHeight(x,y)
16776 #endif
16777 
16778 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
16779 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
16780 
16781 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
16782 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
16783 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
16784 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
16785 #else
16786  #define sqlite3ConnectionBlocked(x,y)
16787  #define sqlite3ConnectionUnlocked(x)
16788  #define sqlite3ConnectionClosed(x)
16789 #endif
16790 
16791 #ifdef SQLITE_DEBUG
16792 SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
16793 #endif
16794 
16795 /*
16796 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
16797 ** sqlite3IoTrace is a pointer to a printf-like routine used to
16798 ** print I/O tracing messages.
16799 */
16800 #ifdef SQLITE_ENABLE_IOTRACE
16801 # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
16802 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
16803 SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
16804 #else
16805 # define IOTRACE(A)
16806 # define sqlite3VdbeIOTraceSql(X)
16807 #endif
16808 
16809 /*
16810 ** These routines are available for the mem2.c debugging memory allocator
16811 ** only. They are used to verify that different "types" of memory
16812 ** allocations are properly tracked by the system.
16813 **
16814 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
16815 ** the MEMTYPE_* macros defined below. The type must be a bitmask with
16816 ** a single bit set.
16817 **
16818 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
16819 ** argument match the type set by the previous sqlite3MemdebugSetType().
16820 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
16821 **
16822 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
16823 ** argument match the type set by the previous sqlite3MemdebugSetType().
16824 **
16825 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
16826 ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
16827 ** it might have been allocated by lookaside, except the allocation was
16828 ** too large or lookaside was already full. It is important to verify
16829 ** that allocations that might have been satisfied by lookaside are not
16830 ** passed back to non-lookaside free() routines. Asserts such as the
16831 ** example above are placed on the non-lookaside free() routines to verify
16832 ** this constraint.
16833 **
16834 ** All of this is no-op for a production build. It only comes into
16835 ** play when the SQLITE_MEMDEBUG compile-time option is used.
16836 */
16837 #ifdef SQLITE_MEMDEBUG
16838 SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
16839 SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
16840 SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
16841 #else
16842 # define sqlite3MemdebugSetType(X,Y) /* no-op */
16843 # define sqlite3MemdebugHasType(X,Y) 1
16844 # define sqlite3MemdebugNoType(X,Y) 1
16845 #endif
16846 #define MEMTYPE_HEAP 0x01 /* General heap allocations */
16847 #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
16848 #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
16849 #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
16850 
16851 /*
16852 ** Threading interface
16853 */
16854 #if SQLITE_MAX_WORKER_THREADS>0
16855 SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
16856 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
16857 #endif
16858 
16859 #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
16860 SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
16861 #endif
16862 
16863 #endif /* SQLITEINT_H */
16864 
16865 /************** End of sqliteInt.h *******************************************/
16866 /************** Begin file global.c ******************************************/
16867 /*
16868 ** 2008 June 13
16869 **
16870 ** The author disclaims copyright to this source code. In place of
16871 ** a legal notice, here is a blessing:
16872 **
16873 ** May you do good and not evil.
16874 ** May you find forgiveness for yourself and forgive others.
16875 ** May you share freely, never taking more than you give.
16876 **
16877 *************************************************************************
16878 **
16879 ** This file contains definitions of global variables and constants.
16880 */
16881 /* #include "sqliteInt.h" */
16882 
16883 /* An array to map all upper-case characters into their corresponding
16884 ** lower-case character.
16885 **
16886 ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
16887 ** handle case conversions for the UTF character set since the tables
16888 ** involved are nearly as big or bigger than SQLite itself.
16889 */
16890 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
16891 #ifdef SQLITE_ASCII
16892  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
16893  18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
16894  36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
16895  54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
16896  104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
16897  122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
16898  108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
16899  126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
16900  144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
16901  162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
16902  180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
16903  198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
16904  216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
16905  234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
16906  252,253,254,255
16907 #endif
16908 #ifdef SQLITE_EBCDIC
16909  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
16910  16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
16911  32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
16912  48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
16913  64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
16914  80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
16915  96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
16916  112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
16917  128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
16918  144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
16919  160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
16920  176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
16921  192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
16922  208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
16923  224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
16924  240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
16925 #endif
16926 };
16927 
16928 /*
16929 ** The following 256 byte lookup table is used to support SQLites built-in
16930 ** equivalents to the following standard library functions:
16931 **
16932 ** isspace() 0x01
16933 ** isalpha() 0x02
16934 ** isdigit() 0x04
16935 ** isalnum() 0x06
16936 ** isxdigit() 0x08
16937 ** toupper() 0x20
16938 ** SQLite identifier character 0x40
16939 ** Quote character 0x80
16940 **
16941 ** Bit 0x20 is set if the mapped character requires translation to upper
16942 ** case. i.e. if the character is a lower-case ASCII character.
16943 ** If x is a lower-case ASCII character, then its upper-case equivalent
16944 ** is (x - 0x20). Therefore toupper() can be implemented as:
16945 **
16946 ** (x & ~(map[x]&0x20))
16947 **
16948 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
16949 ** array. tolower() is used more often than toupper() by SQLite.
16950 **
16951 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
16952 ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
16953 ** non-ASCII UTF character. Hence the test for whether or not a character is
16954 ** part of an identifier is 0x46.
16955 **
16956 ** SQLite's versions are identical to the standard versions assuming a
16957 ** locale of "C". They are implemented as macros in sqliteInt.h.
16958 */
16959 #ifdef SQLITE_ASCII
16960 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
16961  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
16962  0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
16963  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
16964  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
16965  0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80, /* 20..27 !"#$%&' */
16966  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
16967  0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
16968  0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
16969 
16970  0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
16971  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
16972  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
16973  0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
16974  0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
16975  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
16976  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
16977  0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
16978 
16979  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
16980  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
16981  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
16982  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
16983  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
16984  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
16985  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
16986  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
16987 
16988  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
16989  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
16990  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
16991  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
16992  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
16993  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
16994  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
16995  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
16996 };
16997 #endif
16998 
16999 /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
17000 ** compatibility for legacy applications, the URI filename capability is
17001 ** disabled by default.
17002 **
17003 ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
17004 ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
17005 **
17006 ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
17007 ** disabled. The default value may be changed by compiling with the
17008 ** SQLITE_USE_URI symbol defined.
17009 */
17010 #ifndef SQLITE_USE_URI
17011 # define SQLITE_USE_URI 0
17012 #endif
17013 
17014 /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
17015 ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
17016 ** that compile-time option is omitted.
17017 */
17018 #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
17019 # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
17020 #endif
17021 
17022 /* The minimum PMA size is set to this value multiplied by the database
17023 ** page size in bytes.
17024 */
17025 #ifndef SQLITE_SORTER_PMASZ
17026 # define SQLITE_SORTER_PMASZ 250
17027 #endif
17028 
17029 /* Statement journals spill to disk when their size exceeds the following
17030 ** threashold (in bytes). 0 means that statement journals are created and
17031 ** written to disk immediately (the default behavior for SQLite versions
17032 ** before 3.12.0). -1 means always keep the entire statement journal in
17033 ** memory. (The statement journal is also always held entirely in memory
17034 ** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
17035 ** setting.)
17036 */
17037 #ifndef SQLITE_STMTJRNL_SPILL
17038 # define SQLITE_STMTJRNL_SPILL (64*1024)
17039 #endif
17040 
17041 /*
17042 ** The following singleton contains the global configuration for
17043 ** the SQLite library.
17044 */
17045 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
17046  SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
17047  1, /* bCoreMutex */
17048  SQLITE_THREADSAFE==1, /* bFullMutex */
17049  SQLITE_USE_URI, /* bOpenUri */
17050  SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
17051  0x7ffffffe, /* mxStrlen */
17052  0, /* neverCorrupt */
17053  128, /* szLookaside */
17054  500, /* nLookaside */
17055  SQLITE_STMTJRNL_SPILL, /* nStmtSpill */
17056  {0,0,0,0,0,0,0,0}, /* m */
17057  {0,0,0,0,0,0,0,0,0}, /* mutex */
17058  {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
17059  (void*)0, /* pHeap */
17060  0, /* nHeap */
17061  0, 0, /* mnHeap, mxHeap */
17062  SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
17063  SQLITE_MAX_MMAP_SIZE, /* mxMmap */
17064  (void*)0, /* pScratch */
17065  0, /* szScratch */
17066  0, /* nScratch */
17067  (void*)0, /* pPage */
17068  0, /* szPage */
17069  SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
17070  0, /* mxParserStack */
17071  0, /* sharedCacheEnabled */
17072  SQLITE_SORTER_PMASZ, /* szPma */
17073  /* All the rest should always be initialized to zero */
17074  0, /* isInit */
17075  0, /* inProgress */
17076  0, /* isMutexInit */
17077  0, /* isMallocInit */
17078  0, /* isPCacheInit */
17079  0, /* nRefInitMutex */
17080  0, /* pInitMutex */
17081  0, /* xLog */
17082  0, /* pLogArg */
17083 #ifdef SQLITE_ENABLE_SQLLOG
17084  0, /* xSqllog */
17085  0, /* pSqllogArg */
17086 #endif
17087 #ifdef SQLITE_VDBE_COVERAGE
17088  0, /* xVdbeBranch */
17089  0, /* pVbeBranchArg */
17090 #endif
17091 #ifndef SQLITE_OMIT_BUILTIN_TEST
17092  0, /* xTestCallback */
17093 #endif
17094  0 /* bLocaltimeFault */
17095 };
17096 
17097 /*
17098 ** Hash table for global functions - functions common to all
17099 ** database connections. After initialization, this table is
17100 ** read-only.
17101 */
17102 SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
17103 
17104 /*
17105 ** Constant tokens for values 0 and 1.
17106 */
17107 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
17108  { "0", 1 },
17109  { "1", 1 }
17110 };
17111 
17112 
17113 /*
17114 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
17115 ** 1-gibabyte boundary) in a compatible database. SQLite never uses
17116 ** the database page that contains the pending byte. It never attempts
17117 ** to read or write that page. The pending byte page is set assign
17118 ** for use by the VFS layers as space for managing file locks.
17119 **
17120 ** During testing, it is often desirable to move the pending byte to
17121 ** a different position in the file. This allows code that has to
17122 ** deal with the pending byte to run on files that are much smaller
17123 ** than 1 GiB. The sqlite3_test_control() interface can be used to
17124 ** move the pending byte.
17125 **
17126 ** IMPORTANT: Changing the pending byte to any value other than
17127 ** 0x40000000 results in an incompatible database file format!
17128 ** Changing the pending byte during operation will result in undefined
17129 ** and incorrect behavior.
17130 */
17131 #ifndef SQLITE_OMIT_WSD
17132 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
17133 #endif
17134 
17135 /* #include "opcodes.h" */
17136 /*
17137 ** Properties of opcodes. The OPFLG_INITIALIZER macro is
17138 ** created by mkopcodeh.awk during compilation. Data is obtained
17139 ** from the comments following the "case OP_xxxx:" statements in
17140 ** the vdbe.c file.
17141 */
17142 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
17143 
17144 /*
17145 ** Name of the default collating sequence
17146 */
17147 SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
17148 
17149 /************** End of global.c **********************************************/
17150 /************** Begin file ctime.c *******************************************/
17151 /*
17152 ** 2010 February 23
17153 **
17154 ** The author disclaims copyright to this source code. In place of
17155 ** a legal notice, here is a blessing:
17156 **
17157 ** May you do good and not evil.
17158 ** May you find forgiveness for yourself and forgive others.
17159 ** May you share freely, never taking more than you give.
17160 **
17161 *************************************************************************
17162 **
17163 ** This file implements routines used to report what compile-time options
17164 ** SQLite was built with.
17165 */
17166 
17167 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
17168 
17169 /* #include "sqliteInt.h" */
17170 
17171 /*
17172 ** An array of names of all compile-time options. This array should
17173 ** be sorted A-Z.
17174 **
17175 ** This array looks large, but in a typical installation actually uses
17176 ** only a handful of compile-time options, so most times this array is usually
17177 ** rather short and uses little memory space.
17178 */
17179 static const char * const azCompileOpt[] = {
17180 
17181 /* These macros are provided to "stringify" the value of the define
17182 ** for those options in which the value is meaningful. */
17183 #define CTIMEOPT_VAL_(opt) #opt
17184 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
17185 
17186 #if SQLITE_32BIT_ROWID
17187  "32BIT_ROWID",
17188 #endif
17189 #if SQLITE_4_BYTE_ALIGNED_MALLOC
17190  "4_BYTE_ALIGNED_MALLOC",
17191 #endif
17192 #if SQLITE_CASE_SENSITIVE_LIKE
17193  "CASE_SENSITIVE_LIKE",
17194 #endif
17195 #if SQLITE_CHECK_PAGES
17196  "CHECK_PAGES",
17197 #endif
17198 #if defined(__clang__) && defined(__clang_major__)
17199  "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "."
17200  CTIMEOPT_VAL(__clang_minor__) "."
17201  CTIMEOPT_VAL(__clang_patchlevel__),
17202 #elif defined(_MSC_VER)
17203  "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER),
17204 #elif defined(__GNUC__) && defined(__VERSION__)
17205  "COMPILER=gcc-" __VERSION__,
17206 #endif
17207 #if SQLITE_COVERAGE_TEST
17208  "COVERAGE_TEST",
17209 #endif
17210 #if SQLITE_DEBUG
17211  "DEBUG",
17212 #endif
17213 #if SQLITE_DEFAULT_LOCKING_MODE
17214  "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
17215 #endif
17216 #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
17217  "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
17218 #endif
17219 #if SQLITE_DISABLE_DIRSYNC
17220  "DISABLE_DIRSYNC",
17221 #endif
17222 #if SQLITE_DISABLE_LFS
17223  "DISABLE_LFS",
17224 #endif
17225 #if SQLITE_ENABLE_8_3_NAMES
17226  "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES),
17227 #endif
17228 #if SQLITE_ENABLE_API_ARMOR
17229  "ENABLE_API_ARMOR",
17230 #endif
17231 #if SQLITE_ENABLE_ATOMIC_WRITE
17232  "ENABLE_ATOMIC_WRITE",
17233 #endif
17234 #if SQLITE_ENABLE_CEROD
17235  "ENABLE_CEROD",
17236 #endif
17237 #if SQLITE_ENABLE_COLUMN_METADATA
17238  "ENABLE_COLUMN_METADATA",
17239 #endif
17240 #if SQLITE_ENABLE_DBSTAT_VTAB
17241  "ENABLE_DBSTAT_VTAB",
17242 #endif
17243 #if SQLITE_ENABLE_EXPENSIVE_ASSERT
17244  "ENABLE_EXPENSIVE_ASSERT",
17245 #endif
17246 #if SQLITE_ENABLE_FTS1
17247  "ENABLE_FTS1",
17248 #endif
17249 #if SQLITE_ENABLE_FTS2
17250  "ENABLE_FTS2",
17251 #endif
17252 #if SQLITE_ENABLE_FTS3
17253  "ENABLE_FTS3",
17254 #endif
17255 #if SQLITE_ENABLE_FTS3_PARENTHESIS
17256  "ENABLE_FTS3_PARENTHESIS",
17257 #endif
17258 #if SQLITE_ENABLE_FTS4
17259  "ENABLE_FTS4",
17260 #endif
17261 #if SQLITE_ENABLE_FTS5
17262  "ENABLE_FTS5",
17263 #endif
17264 #if SQLITE_ENABLE_ICU
17265  "ENABLE_ICU",
17266 #endif
17267 #if SQLITE_ENABLE_IOTRACE
17268  "ENABLE_IOTRACE",
17269 #endif
17270 #if SQLITE_ENABLE_JSON1
17271  "ENABLE_JSON1",
17272 #endif
17273 #if SQLITE_ENABLE_LOAD_EXTENSION
17274  "ENABLE_LOAD_EXTENSION",
17275 #endif
17276 #if SQLITE_ENABLE_LOCKING_STYLE
17277  "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
17278 #endif
17279 #if SQLITE_ENABLE_MEMORY_MANAGEMENT
17280  "ENABLE_MEMORY_MANAGEMENT",
17281 #endif
17282 #if SQLITE_ENABLE_MEMSYS3
17283  "ENABLE_MEMSYS3",
17284 #endif
17285 #if SQLITE_ENABLE_MEMSYS5
17286  "ENABLE_MEMSYS5",
17287 #endif
17288 #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
17289  "ENABLE_OVERSIZE_CELL_CHECK",
17290 #endif
17291 #if SQLITE_ENABLE_RTREE
17292  "ENABLE_RTREE",
17293 #endif
17294 #if defined(SQLITE_ENABLE_STAT4)
17295  "ENABLE_STAT4",
17296 #elif defined(SQLITE_ENABLE_STAT3)
17297  "ENABLE_STAT3",
17298 #endif
17299 #if SQLITE_ENABLE_UNLOCK_NOTIFY
17300  "ENABLE_UNLOCK_NOTIFY",
17301 #endif
17302 #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
17303  "ENABLE_UPDATE_DELETE_LIMIT",
17304 #endif
17305 #if SQLITE_HAS_CODEC
17306  "HAS_CODEC",
17307 #endif
17308 #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
17309  "HAVE_ISNAN",
17310 #endif
17311 #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17312  "HOMEGROWN_RECURSIVE_MUTEX",
17313 #endif
17314 #if SQLITE_IGNORE_AFP_LOCK_ERRORS
17315  "IGNORE_AFP_LOCK_ERRORS",
17316 #endif
17317 #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
17318  "IGNORE_FLOCK_LOCK_ERRORS",
17319 #endif
17320 #ifdef SQLITE_INT64_TYPE
17321  "INT64_TYPE",
17322 #endif
17323 #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
17324  "LIKE_DOESNT_MATCH_BLOBS",
17325 #endif
17326 #if SQLITE_LOCK_TRACE
17327  "LOCK_TRACE",
17328 #endif
17329 #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
17330  "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
17331 #endif
17332 #ifdef SQLITE_MAX_SCHEMA_RETRY
17333  "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
17334 #endif
17335 #if SQLITE_MEMDEBUG
17336  "MEMDEBUG",
17337 #endif
17338 #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
17339  "MIXED_ENDIAN_64BIT_FLOAT",
17340 #endif
17341 #if SQLITE_NO_SYNC
17342  "NO_SYNC",
17343 #endif
17344 #if SQLITE_OMIT_ALTERTABLE
17345  "OMIT_ALTERTABLE",
17346 #endif
17347 #if SQLITE_OMIT_ANALYZE
17348  "OMIT_ANALYZE",
17349 #endif
17350 #if SQLITE_OMIT_ATTACH
17351  "OMIT_ATTACH",
17352 #endif
17353 #if SQLITE_OMIT_AUTHORIZATION
17354  "OMIT_AUTHORIZATION",
17355 #endif
17356 #if SQLITE_OMIT_AUTOINCREMENT
17357  "OMIT_AUTOINCREMENT",
17358 #endif
17359 #if SQLITE_OMIT_AUTOINIT
17360  "OMIT_AUTOINIT",
17361 #endif
17362 #if SQLITE_OMIT_AUTOMATIC_INDEX
17363  "OMIT_AUTOMATIC_INDEX",
17364 #endif
17365 #if SQLITE_OMIT_AUTORESET
17366  "OMIT_AUTORESET",
17367 #endif
17368 #if SQLITE_OMIT_AUTOVACUUM
17369  "OMIT_AUTOVACUUM",
17370 #endif
17371 #if SQLITE_OMIT_BETWEEN_OPTIMIZATION
17372  "OMIT_BETWEEN_OPTIMIZATION",
17373 #endif
17374 #if SQLITE_OMIT_BLOB_LITERAL
17375  "OMIT_BLOB_LITERAL",
17376 #endif
17377 #if SQLITE_OMIT_BTREECOUNT
17378  "OMIT_BTREECOUNT",
17379 #endif
17380 #if SQLITE_OMIT_BUILTIN_TEST
17381  "OMIT_BUILTIN_TEST",
17382 #endif
17383 #if SQLITE_OMIT_CAST
17384  "OMIT_CAST",
17385 #endif
17386 #if SQLITE_OMIT_CHECK
17387  "OMIT_CHECK",
17388 #endif
17389 #if SQLITE_OMIT_COMPLETE
17390  "OMIT_COMPLETE",
17391 #endif
17392 #if SQLITE_OMIT_COMPOUND_SELECT
17393  "OMIT_COMPOUND_SELECT",
17394 #endif
17395 #if SQLITE_OMIT_CTE
17396  "OMIT_CTE",
17397 #endif
17398 #if SQLITE_OMIT_DATETIME_FUNCS
17399  "OMIT_DATETIME_FUNCS",
17400 #endif
17401 #if SQLITE_OMIT_DECLTYPE
17402  "OMIT_DECLTYPE",
17403 #endif
17404 #if SQLITE_OMIT_DEPRECATED
17405  "OMIT_DEPRECATED",
17406 #endif
17407 #if SQLITE_OMIT_DISKIO
17408  "OMIT_DISKIO",
17409 #endif
17410 #if SQLITE_OMIT_EXPLAIN
17411  "OMIT_EXPLAIN",
17412 #endif
17413 #if SQLITE_OMIT_FLAG_PRAGMAS
17414  "OMIT_FLAG_PRAGMAS",
17415 #endif
17416 #if SQLITE_OMIT_FLOATING_POINT
17417  "OMIT_FLOATING_POINT",
17418 #endif
17419 #if SQLITE_OMIT_FOREIGN_KEY
17420  "OMIT_FOREIGN_KEY",
17421 #endif
17422 #if SQLITE_OMIT_GET_TABLE
17423  "OMIT_GET_TABLE",
17424 #endif
17425 #if SQLITE_OMIT_INCRBLOB
17426  "OMIT_INCRBLOB",
17427 #endif
17428 #if SQLITE_OMIT_INTEGRITY_CHECK
17429  "OMIT_INTEGRITY_CHECK",
17430 #endif
17431 #if SQLITE_OMIT_LIKE_OPTIMIZATION
17432  "OMIT_LIKE_OPTIMIZATION",
17433 #endif
17434 #if SQLITE_OMIT_LOAD_EXTENSION
17435  "OMIT_LOAD_EXTENSION",
17436 #endif
17437 #if SQLITE_OMIT_LOCALTIME
17438  "OMIT_LOCALTIME",
17439 #endif
17440 #if SQLITE_OMIT_LOOKASIDE
17441  "OMIT_LOOKASIDE",
17442 #endif
17443 #if SQLITE_OMIT_MEMORYDB
17444  "OMIT_MEMORYDB",
17445 #endif
17446 #if SQLITE_OMIT_OR_OPTIMIZATION
17447  "OMIT_OR_OPTIMIZATION",
17448 #endif
17449 #if SQLITE_OMIT_PAGER_PRAGMAS
17450  "OMIT_PAGER_PRAGMAS",
17451 #endif
17452 #if SQLITE_OMIT_PRAGMA
17453  "OMIT_PRAGMA",
17454 #endif
17455 #if SQLITE_OMIT_PROGRESS_CALLBACK
17456  "OMIT_PROGRESS_CALLBACK",
17457 #endif
17458 #if SQLITE_OMIT_QUICKBALANCE
17459  "OMIT_QUICKBALANCE",
17460 #endif
17461 #if SQLITE_OMIT_REINDEX
17462  "OMIT_REINDEX",
17463 #endif
17464 #if SQLITE_OMIT_SCHEMA_PRAGMAS
17465  "OMIT_SCHEMA_PRAGMAS",
17466 #endif
17467 #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
17468  "OMIT_SCHEMA_VERSION_PRAGMAS",
17469 #endif
17470 #if SQLITE_OMIT_SHARED_CACHE
17471  "OMIT_SHARED_CACHE",
17472 #endif
17473 #if SQLITE_OMIT_SUBQUERY
17474  "OMIT_SUBQUERY",
17475 #endif
17476 #if SQLITE_OMIT_TCL_VARIABLE
17477  "OMIT_TCL_VARIABLE",
17478 #endif
17479 #if SQLITE_OMIT_TEMPDB
17480  "OMIT_TEMPDB",
17481 #endif
17482 #if SQLITE_OMIT_TRACE
17483  "OMIT_TRACE",
17484 #endif
17485 #if SQLITE_OMIT_TRIGGER
17486  "OMIT_TRIGGER",
17487 #endif
17488 #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
17489  "OMIT_TRUNCATE_OPTIMIZATION",
17490 #endif
17491 #if SQLITE_OMIT_UTF16
17492  "OMIT_UTF16",
17493 #endif
17494 #if SQLITE_OMIT_VACUUM
17495  "OMIT_VACUUM",
17496 #endif
17497 #if SQLITE_OMIT_VIEW
17498  "OMIT_VIEW",
17499 #endif
17500 #if SQLITE_OMIT_VIRTUALTABLE
17501  "OMIT_VIRTUALTABLE",
17502 #endif
17503 #if SQLITE_OMIT_WAL
17504  "OMIT_WAL",
17505 #endif
17506 #if SQLITE_OMIT_WSD
17507  "OMIT_WSD",
17508 #endif
17509 #if SQLITE_OMIT_XFER_OPT
17510  "OMIT_XFER_OPT",
17511 #endif
17512 #if SQLITE_PERFORMANCE_TRACE
17513  "PERFORMANCE_TRACE",
17514 #endif
17515 #if SQLITE_PROXY_DEBUG
17516  "PROXY_DEBUG",
17517 #endif
17518 #if SQLITE_RTREE_INT_ONLY
17519  "RTREE_INT_ONLY",
17520 #endif
17521 #if SQLITE_SECURE_DELETE
17522  "SECURE_DELETE",
17523 #endif
17524 #if SQLITE_SMALL_STACK
17525  "SMALL_STACK",
17526 #endif
17527 #if SQLITE_SOUNDEX
17528  "SOUNDEX",
17529 #endif
17530 #if SQLITE_SYSTEM_MALLOC
17531  "SYSTEM_MALLOC",
17532 #endif
17533 #if SQLITE_TCL
17534  "TCL",
17535 #endif
17536 #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
17537  "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
17538 #endif
17539 #if SQLITE_TEST
17540  "TEST",
17541 #endif
17542 #if defined(SQLITE_THREADSAFE)
17543  "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
17544 #endif
17545 #if SQLITE_USE_ALLOCA
17546  "USE_ALLOCA",
17547 #endif
17548 #if SQLITE_USER_AUTHENTICATION
17549  "USER_AUTHENTICATION",
17550 #endif
17551 #if SQLITE_WIN32_MALLOC
17552  "WIN32_MALLOC",
17553 #endif
17554 #if SQLITE_ZERO_MALLOC
17555  "ZERO_MALLOC"
17556 #endif
17557 };
17558 
17559 /*
17560 ** Given the name of a compile-time option, return true if that option
17561 ** was used and false if not.
17562 **
17563 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
17564 ** is not required for a match.
17565 */
17566 SQLITE_API int SQLITE_STDCALL sqlite3_compileoption_used(const char *zOptName){
17567  int i, n;
17568 
17569 #if SQLITE_ENABLE_API_ARMOR
17570  if( zOptName==0 ){
17571  (void)SQLITE_MISUSE_BKPT;
17572  return 0;
17573  }
17574 #endif
17575  if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
17576  n = sqlite3Strlen30(zOptName);
17577 
17578  /* Since ArraySize(azCompileOpt) is normally in single digits, a
17579  ** linear search is adequate. No need for a binary search. */
17580  for(i=0; i<ArraySize(azCompileOpt); i++){
17581  if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
17582  && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
17583  ){
17584  return 1;
17585  }
17586  }
17587  return 0;
17588 }
17589 
17590 /*
17591 ** Return the N-th compile-time option string. If N is out of range,
17592 ** return a NULL pointer.
17593 */
17594 SQLITE_API const char *SQLITE_STDCALL sqlite3_compileoption_get(int N){
17595  if( N>=0 && N<ArraySize(azCompileOpt) ){
17596  return azCompileOpt[N];
17597  }
17598  return 0;
17599 }
17600 
17601 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
17602 
17603 /************** End of ctime.c ***********************************************/
17604 /************** Begin file status.c ******************************************/
17605 /*
17606 ** 2008 June 18
17607 **
17608 ** The author disclaims copyright to this source code. In place of
17609 ** a legal notice, here is a blessing:
17610 **
17611 ** May you do good and not evil.
17612 ** May you find forgiveness for yourself and forgive others.
17613 ** May you share freely, never taking more than you give.
17614 **
17615 *************************************************************************
17616 **
17617 ** This module implements the sqlite3_status() interface and related
17618 ** functionality.
17619 */
17620 /* #include "sqliteInt.h" */
17621 /************** Include vdbeInt.h in the middle of status.c ******************/
17622 /************** Begin file vdbeInt.h *****************************************/
17623 /*
17624 ** 2003 September 6
17625 **
17626 ** The author disclaims copyright to this source code. In place of
17627 ** a legal notice, here is a blessing:
17628 **
17629 ** May you do good and not evil.
17630 ** May you find forgiveness for yourself and forgive others.
17631 ** May you share freely, never taking more than you give.
17632 **
17633 *************************************************************************
17634 ** This is the header file for information that is private to the
17635 ** VDBE. This information used to all be at the top of the single
17636 ** source code file "vdbe.c". When that file became too big (over
17637 ** 6000 lines long) it was split up into several smaller files and
17638 ** this header information was factored out.
17639 */
17640 #ifndef SQLITE_VDBEINT_H
17641 #define SQLITE_VDBEINT_H
17642 
17643 /*
17644 ** The maximum number of times that a statement will try to reparse
17645 ** itself before giving up and returning SQLITE_SCHEMA.
17646 */
17647 #ifndef SQLITE_MAX_SCHEMA_RETRY
17648 # define SQLITE_MAX_SCHEMA_RETRY 50
17649 #endif
17650 
17651 /*
17652 ** VDBE_DISPLAY_P4 is true or false depending on whether or not the
17653 ** "explain" P4 display logic is enabled.
17654 */
17655 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
17656  || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
17657 # define VDBE_DISPLAY_P4 1
17658 #else
17659 # define VDBE_DISPLAY_P4 0
17660 #endif
17661 
17662 /*
17663 ** SQL is translated into a sequence of instructions to be
17664 ** executed by a virtual machine. Each instruction is an instance
17665 ** of the following structure.
17666 */
17667 typedef struct VdbeOp Op;
17668 
17669 /*
17670 ** Boolean values
17671 */
17672 typedef unsigned Bool;
17673 
17674 /* Opaque type used by code in vdbesort.c */
17675 typedef struct VdbeSorter VdbeSorter;
17676 
17677 /* Opaque type used by the explainer */
17678 typedef struct Explain Explain;
17679 
17680 /* Elements of the linked list at Vdbe.pAuxData */
17681 typedef struct AuxData AuxData;
17682 
17683 /* Types of VDBE cursors */
17684 #define CURTYPE_BTREE 0
17685 #define CURTYPE_SORTER 1
17686 #define CURTYPE_VTAB 2
17687 #define CURTYPE_PSEUDO 3
17688 
17689 /*
17690 ** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
17691 **
17692 ** * A b-tree cursor
17693 ** - In the main database or in an ephemeral database
17694 ** - On either an index or a table
17695 ** * A sorter
17696 ** * A virtual table
17697 ** * A one-row "pseudotable" stored in a single register
17698 */
17699 typedef struct VdbeCursor VdbeCursor;
17700 struct VdbeCursor {
17701  u8 eCurType; /* One of the CURTYPE_* values above */
17702  i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
17703  u8 nullRow; /* True if pointing to a row with no data */
17704  u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
17705  u8 isTable; /* True for rowid tables. False for indexes */
17706 #ifdef SQLITE_DEBUG
17707  u8 seekOp; /* Most recent seek operation on this cursor */
17708  u8 wrFlag; /* The wrFlag argument to sqlite3BtreeCursor() */
17709 #endif
17710  Bool isEphemeral:1; /* True for an ephemeral table */
17711  Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */
17712  Bool isOrdered:1; /* True if the table is not BTREE_UNORDERED */
17713  Pgno pgnoRoot; /* Root page of the open btree cursor */
17714  i16 nField; /* Number of fields in the header */
17715  u16 nHdrParsed; /* Number of header fields parsed so far */
17716  union {
17717  BtCursor *pCursor; /* CURTYPE_BTREE. Btree cursor */
17718  sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */
17719  int pseudoTableReg; /* CURTYPE_PSEUDO. Reg holding content. */
17720  VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */
17721  } uc;
17722  Btree *pBt; /* Separate file holding temporary table */
17723  KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
17724  int seekResult; /* Result of previous sqlite3BtreeMoveto() */
17725  i64 seqCount; /* Sequence counter */
17726  i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
17727  VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
17728  int *aAltMap; /* Mapping from table to index column numbers */
17729 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
17730  u64 maskUsed; /* Mask of columns used by this cursor */
17731 #endif
17732 
17733  /* Cached information about the header for the data record that the
17734  ** cursor is currently pointing to. Only valid if cacheStatus matches
17735  ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
17736  ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
17737  ** the cache is out of date.
17738  **
17739  ** aRow might point to (ephemeral) data for the current row, or it might
17740  ** be NULL.
17741  */
17742  u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
17743  u32 payloadSize; /* Total number of bytes in the record */
17744  u32 szRow; /* Byte available in aRow */
17745  u32 iHdrOffset; /* Offset to next unparsed byte of the header */
17746  const u8 *aRow; /* Data for the current row, if all on one page */
17747  u32 *aOffset; /* Pointer to aType[nField] */
17748  u32 aType[1]; /* Type values for all entries in the record */
17749  /* 2*nField extra array elements allocated for aType[], beyond the one
17750  ** static element declared in the structure. nField total array slots for
17751  ** aType[] and nField+1 array slots for aOffset[] */
17752 };
17753 
17754 /*
17755 ** When a sub-program is executed (OP_Program), a structure of this type
17756 ** is allocated to store the current value of the program counter, as
17757 ** well as the current memory cell array and various other frame specific
17758 ** values stored in the Vdbe struct. When the sub-program is finished,
17759 ** these values are copied back to the Vdbe from the VdbeFrame structure,
17760 ** restoring the state of the VM to as it was before the sub-program
17761 ** began executing.
17762 **
17763 ** The memory for a VdbeFrame object is allocated and managed by a memory
17764 ** cell in the parent (calling) frame. When the memory cell is deleted or
17765 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
17766 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
17767 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
17768 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
17769 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
17770 ** child frame are released.
17771 **
17772 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
17773 ** set to NULL if the currently executing frame is the main program.
17774 */
17775 typedef struct VdbeFrame VdbeFrame;
17776 struct VdbeFrame {
17777  Vdbe *v; /* VM this frame belongs to */
17778  VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
17779  Op *aOp; /* Program instructions for parent frame */
17780  i64 *anExec; /* Event counters from parent frame */
17781  Mem *aMem; /* Array of memory cells for parent frame */
17782  u8 *aOnceFlag; /* Array of OP_Once flags for parent frame */
17783  VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
17784  void *token; /* Copy of SubProgram.token */
17785  i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
17786  AuxData *pAuxData; /* Linked list of auxdata allocations */
17787  int nCursor; /* Number of entries in apCsr */
17788  int pc; /* Program Counter in parent (calling) frame */
17789  int nOp; /* Size of aOp array */
17790  int nMem; /* Number of entries in aMem */
17791  int nOnceFlag; /* Number of entries in aOnceFlag */
17792  int nChildMem; /* Number of memory cells for child frame */
17793  int nChildCsr; /* Number of cursors for child frame */
17794  int nChange; /* Statement changes (Vdbe.nChange) */
17795  int nDbChange; /* Value of db->nChange */
17796 };
17797 
17798 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
17799 
17800 /*
17801 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
17802 */
17803 #define CACHE_STALE 0
17804 
17805 /*
17806 ** Internally, the vdbe manipulates nearly all SQL values as Mem
17807 ** structures. Each Mem struct may cache multiple representations (string,
17808 ** integer etc.) of the same value.
17809 */
17810 struct Mem {
17811  union MemValue {
17812  double r; /* Real value used when MEM_Real is set in flags */
17813  i64 i; /* Integer value used when MEM_Int is set in flags */
17814  int nZero; /* Used when bit MEM_Zero is set in flags */
17815  FuncDef *pDef; /* Used only when flags==MEM_Agg */
17816  RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
17817  VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
17818  } u;
17819  u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
17820  u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
17821  u8 eSubtype; /* Subtype for this value */
17822  int n; /* Number of characters in string value, excluding '\0' */
17823  char *z; /* String or BLOB value */
17824  /* ShallowCopy only needs to copy the information above */
17825  char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
17826  int szMalloc; /* Size of the zMalloc allocation */
17827  u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
17828  sqlite3 *db; /* The associated database connection */
17829  void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
17830 #ifdef SQLITE_DEBUG
17831  Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
17832  void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
17833 #endif
17834 };
17835 
17836 /*
17837 ** Size of struct Mem not including the Mem.zMalloc member or anything that
17838 ** follows.
17839 */
17840 #define MEMCELLSIZE offsetof(Mem,zMalloc)
17841 
17842 /* One or more of the following flags are set to indicate the validOK
17843 ** representations of the value stored in the Mem struct.
17844 **
17845 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
17846 ** No other flags may be set in this case.
17847 **
17848 ** If the MEM_Str flag is set then Mem.z points at a string representation.
17849 ** Usually this is encoded in the same unicode encoding as the main
17850 ** database (see below for exceptions). If the MEM_Term flag is also
17851 ** set, then the string is nul terminated. The MEM_Int and MEM_Real
17852 ** flags may coexist with the MEM_Str flag.
17853 */
17854 #define MEM_Null 0x0001 /* Value is NULL */
17855 #define MEM_Str 0x0002 /* Value is a string */
17856 #define MEM_Int 0x0004 /* Value is an integer */
17857 #define MEM_Real 0x0008 /* Value is a real number */
17858 #define MEM_Blob 0x0010 /* Value is a BLOB */
17859 #define MEM_AffMask 0x001f /* Mask of affinity bits */
17860 #define MEM_RowSet 0x0020 /* Value is a RowSet object */
17861 #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
17862 #define MEM_Undefined 0x0080 /* Value is undefined */
17863 #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
17864 #define MEM_TypeMask 0x81ff /* Mask of type bits */
17865 
17866 
17867 /* Whenever Mem contains a valid string or blob representation, one of
17868 ** the following flags must be set to determine the memory management
17869 ** policy for Mem.z. The MEM_Term flag tells us whether or not the
17870 ** string is \000 or \u0000 terminated
17871 */
17872 #define MEM_Term 0x0200 /* String rep is nul terminated */
17873 #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */
17874 #define MEM_Static 0x0800 /* Mem.z points to a static string */
17875 #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
17876 #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
17877 #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
17878 #define MEM_Subtype 0x8000 /* Mem.eSubtype is valid */
17879 #ifdef SQLITE_OMIT_INCRBLOB
17880  #undef MEM_Zero
17881  #define MEM_Zero 0x0000
17882 #endif
17883 
17884 /* Return TRUE if Mem X contains dynamically allocated content - anything
17885 ** that needs to be deallocated to avoid a leak.
17886 */
17887 #define VdbeMemDynamic(X) \
17888  (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
17889 
17890 /*
17891 ** Clear any existing type flags from a Mem and replace them with f
17892 */
17893 #define MemSetTypeFlag(p, f) \
17894  ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
17895 
17896 /*
17897 ** Return true if a memory cell is not marked as invalid. This macro
17898 ** is for use inside assert() statements only.
17899 */
17900 #ifdef SQLITE_DEBUG
17901 #define memIsValid(M) ((M)->flags & MEM_Undefined)==0
17902 #endif
17903 
17904 /*
17905 ** Each auxiliary data pointer stored by a user defined function
17906 ** implementation calling sqlite3_set_auxdata() is stored in an instance
17907 ** of this structure. All such structures associated with a single VM
17908 ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
17909 ** when the VM is halted (if not before).
17910 */
17911 struct AuxData {
17912  int iOp; /* Instruction number of OP_Function opcode */
17913  int iArg; /* Index of function argument. */
17914  void *pAux; /* Aux data pointer */
17915  void (*xDelete)(void *); /* Destructor for the aux data */
17916  AuxData *pNext; /* Next element in list */
17917 };
17918 
17919 /*
17920 ** The "context" argument for an installable function. A pointer to an
17921 ** instance of this structure is the first argument to the routines used
17922 ** implement the SQL functions.
17923 **
17924 ** There is a typedef for this structure in sqlite.h. So all routines,
17925 ** even the public interface to SQLite, can use a pointer to this structure.
17926 ** But this file is the only place where the internal details of this
17927 ** structure are known.
17928 **
17929 ** This structure is defined inside of vdbeInt.h because it uses substructures
17930 ** (Mem) which are only defined there.
17931 */
17933  Mem *pOut; /* The return value is stored here */
17934  FuncDef *pFunc; /* Pointer to function information */
17935  Mem *pMem; /* Memory cell used to store aggregate context */
17936  Vdbe *pVdbe; /* The VM that owns this context */
17937  int iOp; /* Instruction number of OP_Function */
17938  int isError; /* Error code returned by the function. */
17939  u8 skipFlag; /* Skip accumulator loading if true */
17940  u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */
17941  u8 argc; /* Number of arguments */
17942  sqlite3_value *argv[1]; /* Argument set */
17943 };
17944 
17945 /*
17946 ** An Explain object accumulates indented output which is helpful
17947 ** in describing recursive data structures.
17948 */
17949 struct Explain {
17950  Vdbe *pVdbe; /* Attach the explanation to this Vdbe */
17951  StrAccum str; /* The string being accumulated */
17952  int nIndent; /* Number of elements in aIndent */
17953  u16 aIndent[100]; /* Levels of indentation */
17954  char zBase[100]; /* Initial space */
17955 };
17956 
17957 /* A bitfield type for use inside of structures. Always follow with :N where
17958 ** N is the number of bits.
17959 */
17960 typedef unsigned bft; /* Bit Field Type */
17961 
17962 typedef struct ScanStatus ScanStatus;
17963 struct ScanStatus {
17964  int addrExplain; /* OP_Explain for loop */
17965  int addrLoop; /* Address of "loops" counter */
17966  int addrVisit; /* Address of "rows visited" counter */
17967  int iSelectID; /* The "Select-ID" for this loop */
17968  LogEst nEst; /* Estimated output rows per loop */
17969  char *zName; /* Name of table or index */
17970 };
17971 
17972 /*
17973 ** An instance of the virtual machine. This structure contains the complete
17974 ** state of the virtual machine.
17975 **
17976 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
17977 ** is really a pointer to an instance of this structure.
17978 */
17979 struct Vdbe {
17980  sqlite3 *db; /* The database connection that owns this statement */
17981  Op *aOp; /* Space to hold the virtual machine's program */
17982  Mem *aMem; /* The memory locations */
17983  Mem **apArg; /* Arguments to currently executing user function */
17984  Mem *aColName; /* Column names to return */
17985  Mem *pResultSet; /* Pointer to an array of results */
17986  Parse *pParse; /* Parsing context used to create this Vdbe */
17987  int nMem; /* Number of memory locations currently allocated */
17988  int nOp; /* Number of instructions in the program */
17989  int nCursor; /* Number of slots in apCsr[] */
17990  u32 magic; /* Magic number for sanity checking */
17991  char *zErrMsg; /* Error message written here */
17992  Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
17993  VdbeCursor **apCsr; /* One element of this array for each open cursor */
17994  Mem *aVar; /* Values for the OP_Variable opcode. */
17995  char **azVar; /* Name of variables */
17996  ynVar nVar; /* Number of entries in aVar[] */
17997  ynVar nzVar; /* Number of entries in azVar[] */
17998  u32 cacheCtr; /* VdbeCursor row cache generation counter */
17999  int pc; /* The program counter */
18000  int rc; /* Value to return */
18001 #ifdef SQLITE_DEBUG
18002  int rcApp; /* errcode set by sqlite3_result_error_code() */
18003 #endif
18004  u16 nResColumn; /* Number of columns in one row of the result set */
18005  u8 errorAction; /* Recovery action to do in case of an error */
18006  bft expired:1; /* True if the VM needs to be recompiled */
18007  bft doingRerun:1; /* True if rerunning after an auto-reprepare */
18008  u8 minWriteFileFormat; /* Minimum file format for writable database files */
18009  bft explain:2; /* True if EXPLAIN present on SQL command */
18010  bft changeCntOn:1; /* True to update the change-counter */
18011  bft runOnlyOnce:1; /* Automatically expire on reset */
18012  bft usesStmtJournal:1; /* True if uses a statement journal */
18013  bft readOnly:1; /* True for statements that do not write */
18014  bft bIsReader:1; /* True for statements that read */
18015  bft isPrepareV2:1; /* True if prepared with prepare_v2() */
18016  int nChange; /* Number of db changes made since last reset */
18017  yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
18018  yDbMask lockMask; /* Subset of btreeMask that requires a lock */
18019  int iStatement; /* Statement number (or 0 if has not opened stmt) */
18020  u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */
18021 #ifndef SQLITE_OMIT_TRACE
18022  i64 startTime; /* Time when query started - used for profiling */
18023 #endif
18024  i64 iCurrentTime; /* Value of julianday('now') for this statement */
18025  i64 nFkConstraint; /* Number of imm. FK constraints this VM */
18026  i64 nStmtDefCons; /* Number of def. constraints when stmt started */
18027  i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
18028  char *zSql; /* Text of the SQL statement that generated this */
18029  void *pFree; /* Free this when deleting the vdbe */
18030  VdbeFrame *pFrame; /* Parent frame */
18031  VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
18032  int nFrame; /* Number of frames in pFrame list */
18033  u32 expmask; /* Binding to these vars invalidates VM */
18034  SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
18035  int nOnceFlag; /* Size of array aOnceFlag[] */
18036  u8 *aOnceFlag; /* Flags for OP_Once */
18037  AuxData *pAuxData; /* Linked list of auxdata allocations */
18038 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
18039  i64 *anExec; /* Number of times each op has been executed */
18040  int nScan; /* Entries in aScan[] */
18041  ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */
18042 #endif
18043 };
18044 
18045 /*
18046 ** The following are allowed values for Vdbe.magic
18047 */
18048 #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
18049 #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
18050 #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
18051 #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
18052 
18053 /*
18054 ** Structure used to store the context required by the
18055 ** sqlite3_preupdate_*() API functions.
18056 */
18057 struct PreUpdate {
18058  Vdbe *v;
18059  VdbeCursor *pCsr; /* Cursor to read old values from */
18060  int op; /* One of SQLITE_INSERT, UPDATE, DELETE */
18061  u8 *aRecord; /* old.* database record */
18062  KeyInfo keyinfo;
18063  UnpackedRecord *pUnpacked; /* Unpacked version of aRecord[] */
18064  UnpackedRecord *pNewUnpacked; /* Unpacked version of new.* record */
18065  int iNewReg; /* Register for new.* values */
18066  i64 iKey1; /* First key value passed to hook */
18067  i64 iKey2; /* Second key value passed to hook */
18068  int iPKey; /* If not negative index of IPK column */
18069  Mem *aNew; /* Array of new.* values */
18070 };
18071 
18072 /*
18073 ** Function prototypes
18074 */
18075 SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
18076 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
18077 void sqliteVdbePopStack(Vdbe*,int);
18078 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*);
18079 SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
18080 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
18081 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
18082 #endif
18083 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
18084 SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
18085 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*);
18086 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
18087 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
18088 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
18089 
18090 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
18091 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
18092 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
18093 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
18094 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
18095 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
18096 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
18097 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
18098 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
18099 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
18100 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
18101 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
18102 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
18103 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
18104 #ifdef SQLITE_OMIT_FLOATING_POINT
18105 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
18106 #else
18107 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
18108 #endif
18109 SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
18110 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
18111 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
18112 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
18113 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
18114 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
18115 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
18116 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
18117 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
18118 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
18119 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
18120 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
18121 SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
18122 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,int,Mem*);
18123 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
18124 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
18125 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
18126 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
18127 SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
18128 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
18129 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
18130 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
18131 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
18132 SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);
18133 #endif
18134 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
18135 
18136 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
18137 SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
18138 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
18139 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
18140 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
18141 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
18142 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
18143 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
18144 
18145 #if !defined(SQLITE_OMIT_SHARED_CACHE)
18146 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
18147 #else
18148 # define sqlite3VdbeEnter(X)
18149 #endif
18150 
18151 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
18152 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
18153 #else
18154 # define sqlite3VdbeLeave(X)
18155 #endif
18156 
18157 #ifdef SQLITE_DEBUG
18158 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
18159 SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
18160 #endif
18161 
18162 #ifndef SQLITE_OMIT_FOREIGN_KEY
18163 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
18164 #else
18165 # define sqlite3VdbeCheckFk(p,i) 0
18166 #endif
18167 
18168 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
18169 #ifdef SQLITE_DEBUG
18170 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
18171 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
18172 #endif
18173 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
18174 
18175 #ifndef SQLITE_OMIT_INCRBLOB
18176 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
18177  #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
18178 #else
18179  #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
18180  #define ExpandBlob(P) SQLITE_OK
18181 #endif
18182 
18183 #endif /* !defined(SQLITE_VDBEINT_H) */
18184 
18185 /************** End of vdbeInt.h *********************************************/
18186 /************** Continuing where we left off in status.c *********************/
18187 
18188 /*
18189 ** Variables in which to record status information.
18190 */
18191 #if SQLITE_PTRSIZE>4
18192 typedef sqlite3_int64 sqlite3StatValueType;
18193 #else
18194 typedef u32 sqlite3StatValueType;
18195 #endif
18196 typedef struct sqlite3StatType sqlite3StatType;
18197 static SQLITE_WSD struct sqlite3StatType {
18198  sqlite3StatValueType nowValue[10]; /* Current value */
18199  sqlite3StatValueType mxValue[10]; /* Maximum value */
18200 } sqlite3Stat = { {0,}, {0,} };
18201 
18202 /*
18203 ** Elements of sqlite3Stat[] are protected by either the memory allocator
18204 ** mutex, or by the pcache1 mutex. The following array determines which.
18205 */
18206 static const char statMutex[] = {
18207  0, /* SQLITE_STATUS_MEMORY_USED */
18208  1, /* SQLITE_STATUS_PAGECACHE_USED */
18209  1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
18210  0, /* SQLITE_STATUS_SCRATCH_USED */
18211  0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */
18212  0, /* SQLITE_STATUS_MALLOC_SIZE */
18213  0, /* SQLITE_STATUS_PARSER_STACK */
18214  1, /* SQLITE_STATUS_PAGECACHE_SIZE */
18215  0, /* SQLITE_STATUS_SCRATCH_SIZE */
18216  0, /* SQLITE_STATUS_MALLOC_COUNT */
18217 };
18218 
18219 
18220 /* The "wsdStat" macro will resolve to the status information
18221 ** state vector. If writable static data is unsupported on the target,
18222 ** we have to locate the state vector at run-time. In the more common
18223 ** case where writable static data is supported, wsdStat can refer directly
18224 ** to the "sqlite3Stat" state vector declared above.
18225 */
18226 #ifdef SQLITE_OMIT_WSD
18227 # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
18228 # define wsdStat x[0]
18229 #else
18230 # define wsdStatInit
18231 # define wsdStat sqlite3Stat
18232 #endif
18233 
18234 /*
18235 ** Return the current value of a status parameter. The caller must
18236 ** be holding the appropriate mutex.
18237 */
18238 SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
18239  wsdStatInit;
18240  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18241  assert( op>=0 && op<ArraySize(statMutex) );
18242  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18243  : sqlite3MallocMutex()) );
18244  return wsdStat.nowValue[op];
18245 }
18246 
18247 /*
18248 ** Add N to the value of a status record. The caller must hold the
18249 ** appropriate mutex. (Locking is checked by assert()).
18250 **
18251 ** The StatusUp() routine can accept positive or negative values for N.
18252 ** The value of N is added to the current status value and the high-water
18253 ** mark is adjusted if necessary.
18254 **
18255 ** The StatusDown() routine lowers the current value by N. The highwater
18256 ** mark is unchanged. N must be non-negative for StatusDown().
18257 */
18258 SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
18259  wsdStatInit;
18260  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18261  assert( op>=0 && op<ArraySize(statMutex) );
18262  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18263  : sqlite3MallocMutex()) );
18264  wsdStat.nowValue[op] += N;
18265  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
18266  wsdStat.mxValue[op] = wsdStat.nowValue[op];
18267  }
18268 }
18269 SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
18270  wsdStatInit;
18271  assert( N>=0 );
18272  assert( op>=0 && op<ArraySize(statMutex) );
18273  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18274  : sqlite3MallocMutex()) );
18275  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18276  wsdStat.nowValue[op] -= N;
18277 }
18278 
18279 /*
18280 ** Adjust the highwater mark if necessary.
18281 ** The caller must hold the appropriate mutex.
18282 */
18283 SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){
18284  sqlite3StatValueType newValue;
18285  wsdStatInit;
18286  assert( X>=0 );
18287  newValue = (sqlite3StatValueType)X;
18288  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18289  assert( op>=0 && op<ArraySize(statMutex) );
18290  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18291  : sqlite3MallocMutex()) );
18292  assert( op==SQLITE_STATUS_MALLOC_SIZE
18293  || op==SQLITE_STATUS_PAGECACHE_SIZE
18294  || op==SQLITE_STATUS_SCRATCH_SIZE
18295  || op==SQLITE_STATUS_PARSER_STACK );
18296  if( newValue>wsdStat.mxValue[op] ){
18297  wsdStat.mxValue[op] = newValue;
18298  }
18299 }
18300 
18301 /*
18302 ** Query status information.
18303 */
18304 SQLITE_API int SQLITE_STDCALL sqlite3_status64(
18305  int op,
18306  sqlite3_int64 *pCurrent,
18307  sqlite3_int64 *pHighwater,
18308  int resetFlag
18309 ){
18310  sqlite3_mutex *pMutex;
18311  wsdStatInit;
18312  if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
18313  return SQLITE_MISUSE_BKPT;
18314  }
18315 #ifdef SQLITE_ENABLE_API_ARMOR
18316  if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
18317 #endif
18318  pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
18319  sqlite3_mutex_enter(pMutex);
18320  *pCurrent = wsdStat.nowValue[op];
18321  *pHighwater = wsdStat.mxValue[op];
18322  if( resetFlag ){
18323  wsdStat.mxValue[op] = wsdStat.nowValue[op];
18324  }
18325  sqlite3_mutex_leave(pMutex);
18326  (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */
18327  return SQLITE_OK;
18328 }
18329 SQLITE_API int SQLITE_STDCALL sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
18330  sqlite3_int64 iCur = 0, iHwtr = 0;
18331  int rc;
18332 #ifdef SQLITE_ENABLE_API_ARMOR
18333  if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
18334 #endif
18335  rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
18336  if( rc==0 ){
18337  *pCurrent = (int)iCur;
18338  *pHighwater = (int)iHwtr;
18339  }
18340  return rc;
18341 }
18342 
18343 /*
18344 ** Query status information for a single database connection
18345 */
18346 SQLITE_API int SQLITE_STDCALL sqlite3_db_status(
18347  sqlite3 *db, /* The database connection whose status is desired */
18348  int op, /* Status verb */
18349  int *pCurrent, /* Write current value here */
18350  int *pHighwater, /* Write high-water mark here */
18351  int resetFlag /* Reset high-water mark if true */
18352 ){
18353  int rc = SQLITE_OK; /* Return code */
18354 #ifdef SQLITE_ENABLE_API_ARMOR
18355  if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
18356  return SQLITE_MISUSE_BKPT;
18357  }
18358 #endif
18359  sqlite3_mutex_enter(db->mutex);
18360  switch( op ){
18361  case SQLITE_DBSTATUS_LOOKASIDE_USED: {
18362  *pCurrent = db->lookaside.nOut;
18363  *pHighwater = db->lookaside.mxOut;
18364  if( resetFlag ){
18365  db->lookaside.mxOut = db->lookaside.nOut;
18366  }
18367  break;
18368  }
18369 
18370  case SQLITE_DBSTATUS_LOOKASIDE_HIT:
18371  case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
18372  case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
18373  testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
18374  testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
18375  testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
18376  assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
18377  assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
18378  *pCurrent = 0;
18379  *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
18380  if( resetFlag ){
18381  db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
18382  }
18383  break;
18384  }
18385 
18386  /*
18387  ** Return an approximation for the amount of memory currently used
18388  ** by all pagers associated with the given database connection. The
18389  ** highwater mark is meaningless and is returned as zero.
18390  */
18391  case SQLITE_DBSTATUS_CACHE_USED_SHARED:
18392  case SQLITE_DBSTATUS_CACHE_USED: {
18393  int totalUsed = 0;
18394  int i;
18395  sqlite3BtreeEnterAll(db);
18396  for(i=0; i<db->nDb; i++){
18397  Btree *pBt = db->aDb[i].pBt;
18398  if( pBt ){
18399  Pager *pPager = sqlite3BtreePager(pBt);
18400  int nByte = sqlite3PagerMemUsed(pPager);
18401  if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){
18402  nByte = nByte / sqlite3BtreeConnectionCount(pBt);
18403  }
18404  totalUsed += nByte;
18405  }
18406  }
18407  sqlite3BtreeLeaveAll(db);
18408  *pCurrent = totalUsed;
18409  *pHighwater = 0;
18410  break;
18411  }
18412 
18413  /*
18414  ** *pCurrent gets an accurate estimate of the amount of memory used
18415  ** to store the schema for all databases (main, temp, and any ATTACHed
18416  ** databases. *pHighwater is set to zero.
18417  */
18418  case SQLITE_DBSTATUS_SCHEMA_USED: {
18419  int i; /* Used to iterate through schemas */
18420  int nByte = 0; /* Used to accumulate return value */
18421 
18422  sqlite3BtreeEnterAll(db);
18423  db->pnBytesFreed = &nByte;
18424  for(i=0; i<db->nDb; i++){
18425  Schema *pSchema = db->aDb[i].pSchema;
18426  if( ALWAYS(pSchema!=0) ){
18427  HashElem *p;
18428 
18429  nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
18430  pSchema->tblHash.count
18431  + pSchema->trigHash.count
18432  + pSchema->idxHash.count
18433  + pSchema->fkeyHash.count
18434  );
18435  nByte += sqlite3_msize(pSchema->tblHash.ht);
18436  nByte += sqlite3_msize(pSchema->trigHash.ht);
18437  nByte += sqlite3_msize(pSchema->idxHash.ht);
18438  nByte += sqlite3_msize(pSchema->fkeyHash.ht);
18439 
18440  for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
18441  sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
18442  }
18443  for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
18444  sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
18445  }
18446  }
18447  }
18448  db->pnBytesFreed = 0;
18449  sqlite3BtreeLeaveAll(db);
18450 
18451  *pHighwater = 0;
18452  *pCurrent = nByte;
18453  break;
18454  }
18455 
18456  /*
18457  ** *pCurrent gets an accurate estimate of the amount of memory used
18458  ** to store all prepared statements.
18459  ** *pHighwater is set to zero.
18460  */
18461  case SQLITE_DBSTATUS_STMT_USED: {
18462  struct Vdbe *pVdbe; /* Used to iterate through VMs */
18463  int nByte = 0; /* Used to accumulate return value */
18464 
18465  db->pnBytesFreed = &nByte;
18466  for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
18467  sqlite3VdbeClearObject(db, pVdbe);
18468  sqlite3DbFree(db, pVdbe);
18469  }
18470  db->pnBytesFreed = 0;
18471 
18472  *pHighwater = 0; /* IMP: R-64479-57858 */
18473  *pCurrent = nByte;
18474 
18475  break;
18476  }
18477 
18478  /*
18479  ** Set *pCurrent to the total cache hits or misses encountered by all
18480  ** pagers the database handle is connected to. *pHighwater is always set
18481  ** to zero.
18482  */
18483  case SQLITE_DBSTATUS_CACHE_HIT:
18484  case SQLITE_DBSTATUS_CACHE_MISS:
18485  case SQLITE_DBSTATUS_CACHE_WRITE:{
18486  int i;
18487  int nRet = 0;
18488  assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
18489  assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
18490 
18491  for(i=0; i<db->nDb; i++){
18492  if( db->aDb[i].pBt ){
18493  Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
18494  sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
18495  }
18496  }
18497  *pHighwater = 0; /* IMP: R-42420-56072 */
18498  /* IMP: R-54100-20147 */
18499  /* IMP: R-29431-39229 */
18500  *pCurrent = nRet;
18501  break;
18502  }
18503 
18504  /* Set *pCurrent to non-zero if there are unresolved deferred foreign
18505  ** key constraints. Set *pCurrent to zero if all foreign key constraints
18506  ** have been satisfied. The *pHighwater is always set to zero.
18507  */
18508  case SQLITE_DBSTATUS_DEFERRED_FKS: {
18509  *pHighwater = 0; /* IMP: R-11967-56545 */
18510  *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
18511  break;
18512  }
18513 
18514  default: {
18515  rc = SQLITE_ERROR;
18516  }
18517  }
18518  sqlite3_mutex_leave(db->mutex);
18519  return rc;
18520 }
18521 
18522 /************** End of status.c **********************************************/
18523 /************** Begin file date.c ********************************************/
18524 /*
18525 ** 2003 October 31
18526 **
18527 ** The author disclaims copyright to this source code. In place of
18528 ** a legal notice, here is a blessing:
18529 **
18530 ** May you do good and not evil.
18531 ** May you find forgiveness for yourself and forgive others.
18532 ** May you share freely, never taking more than you give.
18533 **
18534 *************************************************************************
18535 ** This file contains the C functions that implement date and time
18536 ** functions for SQLite.
18537 **
18538 ** There is only one exported symbol in this file - the function
18539 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
18540 ** All other code has file scope.
18541 **
18542 ** SQLite processes all times and dates as julian day numbers. The
18543 ** dates and times are stored as the number of days since noon
18544 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
18545 ** calendar system.
18546 **
18547 ** 1970-01-01 00:00:00 is JD 2440587.5
18548 ** 2000-01-01 00:00:00 is JD 2451544.5
18549 **
18550 ** This implementation requires years to be expressed as a 4-digit number
18551 ** which means that only dates between 0000-01-01 and 9999-12-31 can
18552 ** be represented, even though julian day numbers allow a much wider
18553 ** range of dates.
18554 **
18555 ** The Gregorian calendar system is used for all dates and times,
18556 ** even those that predate the Gregorian calendar. Historians usually
18557 ** use the julian calendar for dates prior to 1582-10-15 and for some
18558 ** dates afterwards, depending on locale. Beware of this difference.
18559 **
18560 ** The conversion algorithms are implemented based on descriptions
18561 ** in the following text:
18562 **
18563 ** Jean Meeus
18564 ** Astronomical Algorithms, 2nd Edition, 1998
18565 ** ISBM 0-943396-61-1
18566 ** Willmann-Bell, Inc
18567 ** Richmond, Virginia (USA)
18568 */
18569 /* #include "sqliteInt.h" */
18570 /* #include <stdlib.h> */
18571 /* #include <assert.h> */
18572 #include <time.h>
18573 
18574 #ifndef SQLITE_OMIT_DATETIME_FUNCS
18575 
18576 /*
18577 ** The MSVC CRT on Windows CE may not have a localtime() function.
18578 ** So declare a substitute. The substitute function itself is
18579 ** defined in "os_win.c".
18580 */
18581 #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
18582  (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
18583 struct tm *__cdecl localtime(const time_t *);
18584 #endif
18585 
18586 /*
18587 ** A structure for holding a single date and time.
18588 */
18589 typedef struct DateTime DateTime;
18590 struct DateTime {
18591  sqlite3_int64 iJD; /* The julian day number times 86400000 */
18592  int Y, M, D; /* Year, month, and day */
18593  int h, m; /* Hour and minutes */
18594  int tz; /* Timezone offset in minutes */
18595  double s; /* Seconds */
18596  char validYMD; /* True (1) if Y,M,D are valid */
18597  char validHMS; /* True (1) if h,m,s are valid */
18598  char validJD; /* True (1) if iJD is valid */
18599  char validTZ; /* True (1) if tz is valid */
18600  char tzSet; /* Timezone was set explicitly */
18601 };
18602 
18603 
18604 /*
18605 ** Convert zDate into one or more integers according to the conversion
18606 ** specifier zFormat.
18607 **
18608 ** zFormat[] contains 4 characters for each integer converted, except for
18609 ** the last integer which is specified by three characters. The meaning
18610 ** of a four-character format specifiers ABCD is:
18611 **
18612 ** A: number of digits to convert. Always "2" or "4".
18613 ** B: minimum value. Always "0" or "1".
18614 ** C: maximum value, decoded as:
18615 ** a: 12
18616 ** b: 14
18617 ** c: 24
18618 ** d: 31
18619 ** e: 59
18620 ** f: 9999
18621 ** D: the separator character, or \000 to indicate this is the
18622 ** last number to convert.
18623 **
18624 ** Example: To translate an ISO-8601 date YYYY-MM-DD, the format would
18625 ** be "40f-21a-20c". The "40f-" indicates the 4-digit year followed by "-".
18626 ** The "21a-" indicates the 2-digit month followed by "-". The "20c" indicates
18627 ** the 2-digit day which is the last integer in the set.
18628 **
18629 ** The function returns the number of successful conversions.
18630 */
18631 static int getDigits(const char *zDate, const char *zFormat, ...){
18632  /* The aMx[] array translates the 3rd character of each format
18633  ** spec into a max size: a b c d e f */
18634  static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };
18635  va_list ap;
18636  int cnt = 0;
18637  char nextC;
18638  va_start(ap, zFormat);
18639  do{
18640  char N = zFormat[0] - '0';
18641  char min = zFormat[1] - '0';
18642  int val = 0;
18643  u16 max;
18644 
18645  assert( zFormat[2]>='a' && zFormat[2]<='f' );
18646  max = aMx[zFormat[2] - 'a'];
18647  nextC = zFormat[3];
18648  val = 0;
18649  while( N-- ){
18650  if( !sqlite3Isdigit(*zDate) ){
18651  goto end_getDigits;
18652  }
18653  val = val*10 + *zDate - '0';
18654  zDate++;
18655  }
18656  if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
18657  goto end_getDigits;
18658  }
18659  *va_arg(ap,int*) = val;
18660  zDate++;
18661  cnt++;
18662  zFormat += 4;
18663  }while( nextC );
18664 end_getDigits:
18665  va_end(ap);
18666  return cnt;
18667 }
18668 
18669 /*
18670 ** Parse a timezone extension on the end of a date-time.
18671 ** The extension is of the form:
18672 **
18673 ** (+/-)HH:MM
18674 **
18675 ** Or the "zulu" notation:
18676 **
18677 ** Z
18678 **
18679 ** If the parse is successful, write the number of minutes
18680 ** of change in p->tz and return 0. If a parser error occurs,
18681 ** return non-zero.
18682 **
18683 ** A missing specifier is not considered an error.
18684 */
18685 static int parseTimezone(const char *zDate, DateTime *p){
18686  int sgn = 0;
18687  int nHr, nMn;
18688  int c;
18689  while( sqlite3Isspace(*zDate) ){ zDate++; }
18690  p->tz = 0;
18691  c = *zDate;
18692  if( c=='-' ){
18693  sgn = -1;
18694  }else if( c=='+' ){
18695  sgn = +1;
18696  }else if( c=='Z' || c=='z' ){
18697  zDate++;
18698  goto zulu_time;
18699  }else{
18700  return c!=0;
18701  }
18702  zDate++;
18703  if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
18704  return 1;
18705  }
18706  zDate += 5;
18707  p->tz = sgn*(nMn + nHr*60);
18708 zulu_time:
18709  while( sqlite3Isspace(*zDate) ){ zDate++; }
18710  p->tzSet = 1;
18711  return *zDate!=0;
18712 }
18713 
18714 /*
18715 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
18716 ** The HH, MM, and SS must each be exactly 2 digits. The
18717 ** fractional seconds FFFF can be one or more digits.
18718 **
18719 ** Return 1 if there is a parsing error and 0 on success.
18720 */
18721 static int parseHhMmSs(const char *zDate, DateTime *p){
18722  int h, m, s;
18723  double ms = 0.0;
18724  if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
18725  return 1;
18726  }
18727  zDate += 5;
18728  if( *zDate==':' ){
18729  zDate++;
18730  if( getDigits(zDate, "20e", &s)!=1 ){
18731  return 1;
18732  }
18733  zDate += 2;
18734  if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
18735  double rScale = 1.0;
18736  zDate++;
18737  while( sqlite3Isdigit(*zDate) ){
18738  ms = ms*10.0 + *zDate - '0';
18739  rScale *= 10.0;
18740  zDate++;
18741  }
18742  ms /= rScale;
18743  }
18744  }else{
18745  s = 0;
18746  }
18747  p->validJD = 0;
18748  p->validHMS = 1;
18749  p->h = h;
18750  p->m = m;
18751  p->s = s + ms;
18752  if( parseTimezone(zDate, p) ) return 1;
18753  p->validTZ = (p->tz!=0)?1:0;
18754  return 0;
18755 }
18756 
18757 /*
18758 ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
18759 ** that the YYYY-MM-DD is according to the Gregorian calendar.
18760 **
18761 ** Reference: Meeus page 61
18762 */
18763 static void computeJD(DateTime *p){
18764  int Y, M, D, A, B, X1, X2;
18765 
18766  if( p->validJD ) return;
18767  if( p->validYMD ){
18768  Y = p->Y;
18769  M = p->M;
18770  D = p->D;
18771  }else{
18772  Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
18773  M = 1;
18774  D = 1;
18775  }
18776  if( M<=2 ){
18777  Y--;
18778  M += 12;
18779  }
18780  A = Y/100;
18781  B = 2 - A + (A/4);
18782  X1 = 36525*(Y+4716)/100;
18783  X2 = 306001*(M+1)/10000;
18784  p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
18785  p->validJD = 1;
18786  if( p->validHMS ){
18787  p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
18788  if( p->validTZ ){
18789  p->iJD -= p->tz*60000;
18790  p->validYMD = 0;
18791  p->validHMS = 0;
18792  p->validTZ = 0;
18793  }
18794  }
18795 }
18796 
18797 /*
18798 ** Parse dates of the form
18799 **
18800 ** YYYY-MM-DD HH:MM:SS.FFF
18801 ** YYYY-MM-DD HH:MM:SS
18802 ** YYYY-MM-DD HH:MM
18803 ** YYYY-MM-DD
18804 **
18805 ** Write the result into the DateTime structure and return 0
18806 ** on success and 1 if the input string is not a well-formed
18807 ** date.
18808 */
18809 static int parseYyyyMmDd(const char *zDate, DateTime *p){
18810  int Y, M, D, neg;
18811 
18812  if( zDate[0]=='-' ){
18813  zDate++;
18814  neg = 1;
18815  }else{
18816  neg = 0;
18817  }
18818  if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
18819  return 1;
18820  }
18821  zDate += 10;
18822  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
18823  if( parseHhMmSs(zDate, p)==0 ){
18824  /* We got the time */
18825  }else if( *zDate==0 ){
18826  p->validHMS = 0;
18827  }else{
18828  return 1;
18829  }
18830  p->validJD = 0;
18831  p->validYMD = 1;
18832  p->Y = neg ? -Y : Y;
18833  p->M = M;
18834  p->D = D;
18835  if( p->validTZ ){
18836  computeJD(p);
18837  }
18838  return 0;
18839 }
18840 
18841 /*
18842 ** Set the time to the current time reported by the VFS.
18843 **
18844 ** Return the number of errors.
18845 */
18846 static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
18847  p->iJD = sqlite3StmtCurrentTime(context);
18848  if( p->iJD>0 ){
18849  p->validJD = 1;
18850  return 0;
18851  }else{
18852  return 1;
18853  }
18854 }
18855 
18856 /*
18857 ** Attempt to parse the given string into a julian day number. Return
18858 ** the number of errors.
18859 **
18860 ** The following are acceptable forms for the input string:
18861 **
18862 ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
18863 ** DDDD.DD
18864 ** now
18865 **
18866 ** In the first form, the +/-HH:MM is always optional. The fractional
18867 ** seconds extension (the ".FFF") is optional. The seconds portion
18868 ** (":SS.FFF") is option. The year and date can be omitted as long
18869 ** as there is a time string. The time string can be omitted as long
18870 ** as there is a year and date.
18871 */
18872 static int parseDateOrTime(
18873  sqlite3_context *context,
18874  const char *zDate,
18875  DateTime *p
18876 ){
18877  double r;
18878  if( parseYyyyMmDd(zDate,p)==0 ){
18879  return 0;
18880  }else if( parseHhMmSs(zDate, p)==0 ){
18881  return 0;
18882  }else if( sqlite3StrICmp(zDate,"now")==0){
18883  return setDateTimeToCurrent(context, p);
18884  }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
18885  p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
18886  p->validJD = 1;
18887  return 0;
18888  }
18889  return 1;
18890 }
18891 
18892 /*
18893 ** Compute the Year, Month, and Day from the julian day number.
18894 */
18895 static void computeYMD(DateTime *p){
18896  int Z, A, B, C, D, E, X1;
18897  if( p->validYMD ) return;
18898  if( !p->validJD ){
18899  p->Y = 2000;
18900  p->M = 1;
18901  p->D = 1;
18902  }else{
18903  Z = (int)((p->iJD + 43200000)/86400000);
18904  A = (int)((Z - 1867216.25)/36524.25);
18905  A = Z + 1 + A - (A/4);
18906  B = A + 1524;
18907  C = (int)((B - 122.1)/365.25);
18908  D = (36525*(C&32767))/100;
18909  E = (int)((B-D)/30.6001);
18910  X1 = (int)(30.6001*E);
18911  p->D = B - D - X1;
18912  p->M = E<14 ? E-1 : E-13;
18913  p->Y = p->M>2 ? C - 4716 : C - 4715;
18914  }
18915  p->validYMD = 1;
18916 }
18917 
18918 /*
18919 ** Compute the Hour, Minute, and Seconds from the julian day number.
18920 */
18921 static void computeHMS(DateTime *p){
18922  int s;
18923  if( p->validHMS ) return;
18924  computeJD(p);
18925  s = (int)((p->iJD + 43200000) % 86400000);
18926  p->s = s/1000.0;
18927  s = (int)p->s;
18928  p->s -= s;
18929  p->h = s/3600;
18930  s -= p->h*3600;
18931  p->m = s/60;
18932  p->s += s - p->m*60;
18933  p->validHMS = 1;
18934 }
18935 
18936 /*
18937 ** Compute both YMD and HMS
18938 */
18939 static void computeYMD_HMS(DateTime *p){
18940  computeYMD(p);
18941  computeHMS(p);
18942 }
18943 
18944 /*
18945 ** Clear the YMD and HMS and the TZ
18946 */
18947 static void clearYMD_HMS_TZ(DateTime *p){
18948  p->validYMD = 0;
18949  p->validHMS = 0;
18950  p->validTZ = 0;
18951 }
18952 
18953 #ifndef SQLITE_OMIT_LOCALTIME
18954 /*
18955 ** On recent Windows platforms, the localtime_s() function is available
18956 ** as part of the "Secure CRT". It is essentially equivalent to
18957 ** localtime_r() available under most POSIX platforms, except that the
18958 ** order of the parameters is reversed.
18959 **
18960 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
18961 **
18962 ** If the user has not indicated to use localtime_r() or localtime_s()
18963 ** already, check for an MSVC build environment that provides
18964 ** localtime_s().
18965 */
18966 #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
18967  && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
18968 #undef HAVE_LOCALTIME_S
18969 #define HAVE_LOCALTIME_S 1
18970 #endif
18971 
18972 /*
18973 ** The following routine implements the rough equivalent of localtime_r()
18974 ** using whatever operating-system specific localtime facility that
18975 ** is available. This routine returns 0 on success and
18976 ** non-zero on any kind of error.
18977 **
18978 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
18979 ** routine will always fail.
18980 **
18981 ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
18982 ** library function localtime_r() is used to assist in the calculation of
18983 ** local time.
18984 */
18985 static int osLocaltime(time_t *t, struct tm *pTm){
18986  int rc;
18987 #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
18988  struct tm *pX;
18989 #if SQLITE_THREADSAFE>0
18990  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
18991 #endif
18992  sqlite3_mutex_enter(mutex);
18993  pX = localtime(t);
18994 #ifndef SQLITE_OMIT_BUILTIN_TEST
18995  if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
18996 #endif
18997  if( pX ) *pTm = *pX;
18998  sqlite3_mutex_leave(mutex);
18999  rc = pX==0;
19000 #else
19001 #ifndef SQLITE_OMIT_BUILTIN_TEST
19002  if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
19003 #endif
19004 #if HAVE_LOCALTIME_R
19005  rc = localtime_r(t, pTm)==0;
19006 #else
19007  rc = localtime_s(pTm, t);
19008 #endif /* HAVE_LOCALTIME_R */
19009 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
19010  return rc;
19011 }
19012 #endif /* SQLITE_OMIT_LOCALTIME */
19013 
19014 
19015 #ifndef SQLITE_OMIT_LOCALTIME
19016 /*
19017 ** Compute the difference (in milliseconds) between localtime and UTC
19018 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
19019 ** return this value and set *pRc to SQLITE_OK.
19020 **
19021 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
19022 ** is undefined in this case.
19023 */
19024 static sqlite3_int64 localtimeOffset(
19025  DateTime *p, /* Date at which to calculate offset */
19026  sqlite3_context *pCtx, /* Write error here if one occurs */
19027  int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
19028 ){
19029  DateTime x, y;
19030  time_t t;
19031  struct tm sLocal;
19032 
19033  /* Initialize the contents of sLocal to avoid a compiler warning. */
19034  memset(&sLocal, 0, sizeof(sLocal));
19035 
19036  x = *p;
19037  computeYMD_HMS(&x);
19038  if( x.Y<1971 || x.Y>=2038 ){
19039  /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
19040  ** works for years between 1970 and 2037. For dates outside this range,
19041  ** SQLite attempts to map the year into an equivalent year within this
19042  ** range, do the calculation, then map the year back.
19043  */
19044  x.Y = 2000;
19045  x.M = 1;
19046  x.D = 1;
19047  x.h = 0;
19048  x.m = 0;
19049  x.s = 0.0;
19050  } else {
19051  int s = (int)(x.s + 0.5);
19052  x.s = s;
19053  }
19054  x.tz = 0;
19055  x.validJD = 0;
19056  computeJD(&x);
19057  t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
19058  if( osLocaltime(&t, &sLocal) ){
19059  sqlite3_result_error(pCtx, "local time unavailable", -1);
19060  *pRc = SQLITE_ERROR;
19061  return 0;
19062  }
19063  y.Y = sLocal.tm_year + 1900;
19064  y.M = sLocal.tm_mon + 1;
19065  y.D = sLocal.tm_mday;
19066  y.h = sLocal.tm_hour;
19067  y.m = sLocal.tm_min;
19068  y.s = sLocal.tm_sec;
19069  y.validYMD = 1;
19070  y.validHMS = 1;
19071  y.validJD = 0;
19072  y.validTZ = 0;
19073  computeJD(&y);
19074  *pRc = SQLITE_OK;
19075  return y.iJD - x.iJD;
19076 }
19077 #endif /* SQLITE_OMIT_LOCALTIME */
19078 
19079 /*
19080 ** Process a modifier to a date-time stamp. The modifiers are
19081 ** as follows:
19082 **
19083 ** NNN days
19084 ** NNN hours
19085 ** NNN minutes
19086 ** NNN.NNNN seconds
19087 ** NNN months
19088 ** NNN years
19089 ** start of month
19090 ** start of year
19091 ** start of week
19092 ** start of day
19093 ** weekday N
19094 ** unixepoch
19095 ** localtime
19096 ** utc
19097 **
19098 ** Return 0 on success and 1 if there is any kind of error. If the error
19099 ** is in a system call (i.e. localtime()), then an error message is written
19100 ** to context pCtx. If the error is an unrecognized modifier, no error is
19101 ** written to pCtx.
19102 */
19103 static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
19104  int rc = 1;
19105  int n;
19106  double r;
19107  char *z, zBuf[30];
19108  z = zBuf;
19109  for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
19110  z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
19111  }
19112  z[n] = 0;
19113  switch( z[0] ){
19114 #ifndef SQLITE_OMIT_LOCALTIME
19115  case 'l': {
19116  /* localtime
19117  **
19118  ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
19119  ** show local time.
19120  */
19121  if( strcmp(z, "localtime")==0 ){
19122  computeJD(p);
19123  p->iJD += localtimeOffset(p, pCtx, &rc);
19124  clearYMD_HMS_TZ(p);
19125  }
19126  break;
19127  }
19128 #endif
19129  case 'u': {
19130  /*
19131  ** unixepoch
19132  **
19133  ** Treat the current value of p->iJD as the number of
19134  ** seconds since 1970. Convert to a real julian day number.
19135  */
19136  if( strcmp(z, "unixepoch")==0 && p->validJD ){
19137  p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
19138  clearYMD_HMS_TZ(p);
19139  rc = 0;
19140  }
19141 #ifndef SQLITE_OMIT_LOCALTIME
19142  else if( strcmp(z, "utc")==0 ){
19143  if( p->tzSet==0 ){
19144  sqlite3_int64 c1;
19145  computeJD(p);
19146  c1 = localtimeOffset(p, pCtx, &rc);
19147  if( rc==SQLITE_OK ){
19148  p->iJD -= c1;
19149  clearYMD_HMS_TZ(p);
19150  p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
19151  }
19152  p->tzSet = 1;
19153  }else{
19154  rc = SQLITE_OK;
19155  }
19156  }
19157 #endif
19158  break;
19159  }
19160  case 'w': {
19161  /*
19162  ** weekday N
19163  **
19164  ** Move the date to the same time on the next occurrence of
19165  ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
19166  ** date is already on the appropriate weekday, this is a no-op.
19167  */
19168  if( strncmp(z, "weekday ", 8)==0
19169  && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
19170  && (n=(int)r)==r && n>=0 && r<7 ){
19171  sqlite3_int64 Z;
19172  computeYMD_HMS(p);
19173  p->validTZ = 0;
19174  p->validJD = 0;
19175  computeJD(p);
19176  Z = ((p->iJD + 129600000)/86400000) % 7;
19177  if( Z>n ) Z -= 7;
19178  p->iJD += (n - Z)*86400000;
19179  clearYMD_HMS_TZ(p);
19180  rc = 0;
19181  }
19182  break;
19183  }
19184  case 's': {
19185  /*
19186  ** start of TTTTT
19187  **
19188  ** Move the date backwards to the beginning of the current day,
19189  ** or month or year.
19190  */
19191  if( strncmp(z, "start of ", 9)!=0 ) break;
19192  z += 9;
19193  computeYMD(p);
19194  p->validHMS = 1;
19195  p->h = p->m = 0;
19196  p->s = 0.0;
19197  p->validTZ = 0;
19198  p->validJD = 0;
19199  if( strcmp(z,"month")==0 ){
19200  p->D = 1;
19201  rc = 0;
19202  }else if( strcmp(z,"year")==0 ){
19203  computeYMD(p);
19204  p->M = 1;
19205  p->D = 1;
19206  rc = 0;
19207  }else if( strcmp(z,"day")==0 ){
19208  rc = 0;
19209  }
19210  break;
19211  }
19212  case '+':
19213  case '-':
19214  case '0':
19215  case '1':
19216  case '2':
19217  case '3':
19218  case '4':
19219  case '5':
19220  case '6':
19221  case '7':
19222  case '8':
19223  case '9': {
19224  double rRounder;
19225  for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
19226  if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
19227  rc = 1;
19228  break;
19229  }
19230  if( z[n]==':' ){
19231  /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
19232  ** specified number of hours, minutes, seconds, and fractional seconds
19233  ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
19234  ** omitted.
19235  */
19236  const char *z2 = z;
19237  DateTime tx;
19238  sqlite3_int64 day;
19239  if( !sqlite3Isdigit(*z2) ) z2++;
19240  memset(&tx, 0, sizeof(tx));
19241  if( parseHhMmSs(z2, &tx) ) break;
19242  computeJD(&tx);
19243  tx.iJD -= 43200000;
19244  day = tx.iJD/86400000;
19245  tx.iJD -= day*86400000;
19246  if( z[0]=='-' ) tx.iJD = -tx.iJD;
19247  computeJD(p);
19248  clearYMD_HMS_TZ(p);
19249  p->iJD += tx.iJD;
19250  rc = 0;
19251  break;
19252  }
19253  z += n;
19254  while( sqlite3Isspace(*z) ) z++;
19255  n = sqlite3Strlen30(z);
19256  if( n>10 || n<3 ) break;
19257  if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
19258  computeJD(p);
19259  rc = 0;
19260  rRounder = r<0 ? -0.5 : +0.5;
19261  if( n==3 && strcmp(z,"day")==0 ){
19262  p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
19263  }else if( n==4 && strcmp(z,"hour")==0 ){
19264  p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
19265  }else if( n==6 && strcmp(z,"minute")==0 ){
19266  p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
19267  }else if( n==6 && strcmp(z,"second")==0 ){
19268  p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
19269  }else if( n==5 && strcmp(z,"month")==0 ){
19270  int x, y;
19271  computeYMD_HMS(p);
19272  p->M += (int)r;
19273  x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
19274  p->Y += x;
19275  p->M -= x*12;
19276  p->validJD = 0;
19277  computeJD(p);
19278  y = (int)r;
19279  if( y!=r ){
19280  p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
19281  }
19282  }else if( n==4 && strcmp(z,"year")==0 ){
19283  int y = (int)r;
19284  computeYMD_HMS(p);
19285  p->Y += y;
19286  p->validJD = 0;
19287  computeJD(p);
19288  if( y!=r ){
19289  p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
19290  }
19291  }else{
19292  rc = 1;
19293  }
19294  clearYMD_HMS_TZ(p);
19295  break;
19296  }
19297  default: {
19298  break;
19299  }
19300  }
19301  return rc;
19302 }
19303 
19304 /*
19305 ** Process time function arguments. argv[0] is a date-time stamp.
19306 ** argv[1] and following are modifiers. Parse them all and write
19307 ** the resulting time into the DateTime structure p. Return 0
19308 ** on success and 1 if there are any errors.
19309 **
19310 ** If there are zero parameters (if even argv[0] is undefined)
19311 ** then assume a default value of "now" for argv[0].
19312 */
19313 static int isDate(
19314  sqlite3_context *context,
19315  int argc,
19316  sqlite3_value **argv,
19317  DateTime *p
19318 ){
19319  int i;
19320  const unsigned char *z;
19321  int eType;
19322  memset(p, 0, sizeof(*p));
19323  if( argc==0 ){
19324  return setDateTimeToCurrent(context, p);
19325  }
19326  if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
19327  || eType==SQLITE_INTEGER ){
19328  p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
19329  p->validJD = 1;
19330  }else{
19331  z = sqlite3_value_text(argv[0]);
19332  if( !z || parseDateOrTime(context, (char*)z, p) ){
19333  return 1;
19334  }
19335  }
19336  for(i=1; i<argc; i++){
19337  z = sqlite3_value_text(argv[i]);
19338  if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
19339  }
19340  return 0;
19341 }
19342 
19343 
19344 /*
19345 ** The following routines implement the various date and time functions
19346 ** of SQLite.
19347 */
19348 
19349 /*
19350 ** julianday( TIMESTRING, MOD, MOD, ...)
19351 **
19352 ** Return the julian day number of the date specified in the arguments
19353 */
19354 static void juliandayFunc(
19355  sqlite3_context *context,
19356  int argc,
19357  sqlite3_value **argv
19358 ){
19359  DateTime x;
19360  if( isDate(context, argc, argv, &x)==0 ){
19361  computeJD(&x);
19362  sqlite3_result_double(context, x.iJD/86400000.0);
19363  }
19364 }
19365 
19366 /*
19367 ** datetime( TIMESTRING, MOD, MOD, ...)
19368 **
19369 ** Return YYYY-MM-DD HH:MM:SS
19370 */
19371 static void datetimeFunc(
19372  sqlite3_context *context,
19373  int argc,
19374  sqlite3_value **argv
19375 ){
19376  DateTime x;
19377  if( isDate(context, argc, argv, &x)==0 ){
19378  char zBuf[100];
19379  computeYMD_HMS(&x);
19380  sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
19381  x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
19382  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19383  }
19384 }
19385 
19386 /*
19387 ** time( TIMESTRING, MOD, MOD, ...)
19388 **
19389 ** Return HH:MM:SS
19390 */
19391 static void timeFunc(
19392  sqlite3_context *context,
19393  int argc,
19394  sqlite3_value **argv
19395 ){
19396  DateTime x;
19397  if( isDate(context, argc, argv, &x)==0 ){
19398  char zBuf[100];
19399  computeHMS(&x);
19400  sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
19401  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19402  }
19403 }
19404 
19405 /*
19406 ** date( TIMESTRING, MOD, MOD, ...)
19407 **
19408 ** Return YYYY-MM-DD
19409 */
19410 static void dateFunc(
19411  sqlite3_context *context,
19412  int argc,
19413  sqlite3_value **argv
19414 ){
19415  DateTime x;
19416  if( isDate(context, argc, argv, &x)==0 ){
19417  char zBuf[100];
19418  computeYMD(&x);
19419  sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
19420  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19421  }
19422 }
19423 
19424 /*
19425 ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
19426 **
19427 ** Return a string described by FORMAT. Conversions as follows:
19428 **
19429 ** %d day of month
19430 ** %f ** fractional seconds SS.SSS
19431 ** %H hour 00-24
19432 ** %j day of year 000-366
19433 ** %J ** julian day number
19434 ** %m month 01-12
19435 ** %M minute 00-59
19436 ** %s seconds since 1970-01-01
19437 ** %S seconds 00-59
19438 ** %w day of week 0-6 sunday==0
19439 ** %W week of year 00-53
19440 ** %Y year 0000-9999
19441 ** %% %
19442 */
19443 static void strftimeFunc(
19444  sqlite3_context *context,
19445  int argc,
19446  sqlite3_value **argv
19447 ){
19448  DateTime x;
19449  u64 n;
19450  size_t i,j;
19451  char *z;
19452  sqlite3 *db;
19453  const char *zFmt;
19454  char zBuf[100];
19455  if( argc==0 ) return;
19456  zFmt = (const char*)sqlite3_value_text(argv[0]);
19457  if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
19458  db = sqlite3_context_db_handle(context);
19459  for(i=0, n=1; zFmt[i]; i++, n++){
19460  if( zFmt[i]=='%' ){
19461  switch( zFmt[i+1] ){
19462  case 'd':
19463  case 'H':
19464  case 'm':
19465  case 'M':
19466  case 'S':
19467  case 'W':
19468  n++;
19469  /* fall thru */
19470  case 'w':
19471  case '%':
19472  break;
19473  case 'f':
19474  n += 8;
19475  break;
19476  case 'j':
19477  n += 3;
19478  break;
19479  case 'Y':
19480  n += 8;
19481  break;
19482  case 's':
19483  case 'J':
19484  n += 50;
19485  break;
19486  default:
19487  return; /* ERROR. return a NULL */
19488  }
19489  i++;
19490  }
19491  }
19492  testcase( n==sizeof(zBuf)-1 );
19493  testcase( n==sizeof(zBuf) );
19494  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
19495  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
19496  if( n<sizeof(zBuf) ){
19497  z = zBuf;
19498  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
19499  sqlite3_result_error_toobig(context);
19500  return;
19501  }else{
19502  z = sqlite3DbMallocRawNN(db, (int)n);
19503  if( z==0 ){
19504  sqlite3_result_error_nomem(context);
19505  return;
19506  }
19507  }
19508  computeJD(&x);
19509  computeYMD_HMS(&x);
19510  for(i=j=0; zFmt[i]; i++){
19511  if( zFmt[i]!='%' ){
19512  z[j++] = zFmt[i];
19513  }else{
19514  i++;
19515  switch( zFmt[i] ){
19516  case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
19517  case 'f': {
19518  double s = x.s;
19519  if( s>59.999 ) s = 59.999;
19520  sqlite3_snprintf(7, &z[j],"%06.3f", s);
19521  j += sqlite3Strlen30(&z[j]);
19522  break;
19523  }
19524  case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
19525  case 'W': /* Fall thru */
19526  case 'j': {
19527  int nDay; /* Number of days since 1st day of year */
19528  DateTime y = x;
19529  y.validJD = 0;
19530  y.M = 1;
19531  y.D = 1;
19532  computeJD(&y);
19533  nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
19534  if( zFmt[i]=='W' ){
19535  int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
19536  wd = (int)(((x.iJD+43200000)/86400000)%7);
19537  sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
19538  j += 2;
19539  }else{
19540  sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
19541  j += 3;
19542  }
19543  break;
19544  }
19545  case 'J': {
19546  sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
19547  j+=sqlite3Strlen30(&z[j]);
19548  break;
19549  }
19550  case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
19551  case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
19552  case 's': {
19553  sqlite3_snprintf(30,&z[j],"%lld",
19554  (i64)(x.iJD/1000 - 21086676*(i64)10000));
19555  j += sqlite3Strlen30(&z[j]);
19556  break;
19557  }
19558  case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
19559  case 'w': {
19560  z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
19561  break;
19562  }
19563  case 'Y': {
19564  sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
19565  break;
19566  }
19567  default: z[j++] = '%'; break;
19568  }
19569  }
19570  }
19571  z[j] = 0;
19572  sqlite3_result_text(context, z, -1,
19573  z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
19574 }
19575 
19576 /*
19577 ** current_time()
19578 **
19579 ** This function returns the same value as time('now').
19580 */
19581 static void ctimeFunc(
19582  sqlite3_context *context,
19583  int NotUsed,
19584  sqlite3_value **NotUsed2
19585 ){
19586  UNUSED_PARAMETER2(NotUsed, NotUsed2);
19587  timeFunc(context, 0, 0);
19588 }
19589 
19590 /*
19591 ** current_date()
19592 **
19593 ** This function returns the same value as date('now').
19594 */
19595 static void cdateFunc(
19596  sqlite3_context *context,
19597  int NotUsed,
19598  sqlite3_value **NotUsed2
19599 ){
19600  UNUSED_PARAMETER2(NotUsed, NotUsed2);
19601  dateFunc(context, 0, 0);
19602 }
19603 
19604 /*
19605 ** current_timestamp()
19606 **
19607 ** This function returns the same value as datetime('now').
19608 */
19609 static void ctimestampFunc(
19610  sqlite3_context *context,
19611  int NotUsed,
19612  sqlite3_value **NotUsed2
19613 ){
19614  UNUSED_PARAMETER2(NotUsed, NotUsed2);
19615  datetimeFunc(context, 0, 0);
19616 }
19617 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
19618 
19619 #ifdef SQLITE_OMIT_DATETIME_FUNCS
19620 /*
19621 ** If the library is compiled to omit the full-scale date and time
19622 ** handling (to get a smaller binary), the following minimal version
19623 ** of the functions current_time(), current_date() and current_timestamp()
19624 ** are included instead. This is to support column declarations that
19625 ** include "DEFAULT CURRENT_TIME" etc.
19626 **
19627 ** This function uses the C-library functions time(), gmtime()
19628 ** and strftime(). The format string to pass to strftime() is supplied
19629 ** as the user-data for the function.
19630 */
19631 static void currentTimeFunc(
19632  sqlite3_context *context,
19633  int argc,
19634  sqlite3_value **argv
19635 ){
19636  time_t t;
19637  char *zFormat = (char *)sqlite3_user_data(context);
19638  sqlite3_int64 iT;
19639  struct tm *pTm;
19640  struct tm sNow;
19641  char zBuf[20];
19642 
19643  UNUSED_PARAMETER(argc);
19644  UNUSED_PARAMETER(argv);
19645 
19646  iT = sqlite3StmtCurrentTime(context);
19647  if( iT<=0 ) return;
19648  t = iT/1000 - 10000*(sqlite3_int64)21086676;
19649 #if HAVE_GMTIME_R
19650  pTm = gmtime_r(&t, &sNow);
19651 #else
19652  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
19653  pTm = gmtime(&t);
19654  if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
19655  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
19656 #endif
19657  if( pTm ){
19658  strftime(zBuf, 20, zFormat, &sNow);
19659  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19660  }
19661 }
19662 #endif
19663 
19664 /*
19665 ** This function registered all of the above C functions as SQL
19666 ** functions. This should be the only routine in this file with
19667 ** external linkage.
19668 */
19669 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
19670  static FuncDef aDateTimeFuncs[] = {
19671 #ifndef SQLITE_OMIT_DATETIME_FUNCS
19672  DFUNCTION(julianday, -1, 0, 0, juliandayFunc ),
19673  DFUNCTION(date, -1, 0, 0, dateFunc ),
19674  DFUNCTION(time, -1, 0, 0, timeFunc ),
19675  DFUNCTION(datetime, -1, 0, 0, datetimeFunc ),
19676  DFUNCTION(strftime, -1, 0, 0, strftimeFunc ),
19677  DFUNCTION(current_time, 0, 0, 0, ctimeFunc ),
19678  DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
19679  DFUNCTION(current_date, 0, 0, 0, cdateFunc ),
19680 #else
19681  STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
19682  STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
19683  STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
19684 #endif
19685  };
19686  sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
19687 }
19688 
19689 /************** End of date.c ************************************************/
19690 /************** Begin file os.c **********************************************/
19691 /*
19692 ** 2005 November 29
19693 **
19694 ** The author disclaims copyright to this source code. In place of
19695 ** a legal notice, here is a blessing:
19696 **
19697 ** May you do good and not evil.
19698 ** May you find forgiveness for yourself and forgive others.
19699 ** May you share freely, never taking more than you give.
19700 **
19701 ******************************************************************************
19702 **
19703 ** This file contains OS interface code that is common to all
19704 ** architectures.
19705 */
19706 /* #include "sqliteInt.h" */
19707 
19708 /*
19709 ** If we compile with the SQLITE_TEST macro set, then the following block
19710 ** of code will give us the ability to simulate a disk I/O error. This
19711 ** is used for testing the I/O recovery logic.
19712 */
19713 #if defined(SQLITE_TEST)
19714 SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
19715 SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
19716 SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
19717 SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
19718 SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
19719 SQLITE_API int sqlite3_diskfull_pending = 0;
19720 SQLITE_API int sqlite3_diskfull = 0;
19721 #endif /* defined(SQLITE_TEST) */
19722 
19723 /*
19724 ** When testing, also keep a count of the number of open files.
19725 */
19726 #if defined(SQLITE_TEST)
19727 SQLITE_API int sqlite3_open_file_count = 0;
19728 #endif /* defined(SQLITE_TEST) */
19729 
19730 /*
19731 ** The default SQLite sqlite3_vfs implementations do not allocate
19732 ** memory (actually, os_unix.c allocates a small amount of memory
19733 ** from within OsOpen()), but some third-party implementations may.
19734 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
19735 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
19736 **
19737 ** The following functions are instrumented for malloc() failure
19738 ** testing:
19739 **
19740 ** sqlite3OsRead()
19741 ** sqlite3OsWrite()
19742 ** sqlite3OsSync()
19743 ** sqlite3OsFileSize()
19744 ** sqlite3OsLock()
19745 ** sqlite3OsCheckReservedLock()
19746 ** sqlite3OsFileControl()
19747 ** sqlite3OsShmMap()
19748 ** sqlite3OsOpen()
19749 ** sqlite3OsDelete()
19750 ** sqlite3OsAccess()
19751 ** sqlite3OsFullPathname()
19752 **
19753 */
19754 #if defined(SQLITE_TEST)
19755 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
19756  #define DO_OS_MALLOC_TEST(x) \
19757  if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
19758  void *pTstAlloc = sqlite3Malloc(10); \
19759  if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT; \
19760  sqlite3_free(pTstAlloc); \
19761  }
19762 #else
19763  #define DO_OS_MALLOC_TEST(x)
19764 #endif
19765 
19766 /*
19767 ** The following routines are convenience wrappers around methods
19768 ** of the sqlite3_file object. This is mostly just syntactic sugar. All
19769 ** of this would be completely automatic if SQLite were coded using
19770 ** C++ instead of plain old C.
19771 */
19772 SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
19773  if( pId->pMethods ){
19774  pId->pMethods->xClose(pId);
19775  pId->pMethods = 0;
19776  }
19777 }
19778 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
19779  DO_OS_MALLOC_TEST(id);
19780  return id->pMethods->xRead(id, pBuf, amt, offset);
19781 }
19782 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
19783  DO_OS_MALLOC_TEST(id);
19784  return id->pMethods->xWrite(id, pBuf, amt, offset);
19785 }
19786 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
19787  return id->pMethods->xTruncate(id, size);
19788 }
19789 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
19790  DO_OS_MALLOC_TEST(id);
19791  return id->pMethods->xSync(id, flags);
19792 }
19793 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
19794  DO_OS_MALLOC_TEST(id);
19795  return id->pMethods->xFileSize(id, pSize);
19796 }
19797 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
19798  DO_OS_MALLOC_TEST(id);
19799  return id->pMethods->xLock(id, lockType);
19800 }
19801 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
19802  return id->pMethods->xUnlock(id, lockType);
19803 }
19804 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
19805  DO_OS_MALLOC_TEST(id);
19806  return id->pMethods->xCheckReservedLock(id, pResOut);
19807 }
19808 
19809 /*
19810 ** Use sqlite3OsFileControl() when we are doing something that might fail
19811 ** and we need to know about the failures. Use sqlite3OsFileControlHint()
19812 ** when simply tossing information over the wall to the VFS and we do not
19813 ** really care if the VFS receives and understands the information since it
19814 ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
19815 ** routine has no return value since the return value would be meaningless.
19816 */
19817 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
19818 #ifdef SQLITE_TEST
19819  if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
19820  /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
19821  ** is using a regular VFS, it is called after the corresponding
19822  ** transaction has been committed. Injecting a fault at this point
19823  ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
19824  ** but the transaction is committed anyway.
19825  **
19826  ** The core must call OsFileControl() though, not OsFileControlHint(),
19827  ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
19828  ** means the commit really has failed and an error should be returned
19829  ** to the user. */
19830  DO_OS_MALLOC_TEST(id);
19831  }
19832 #endif
19833  return id->pMethods->xFileControl(id, op, pArg);
19834 }
19835 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
19836  (void)id->pMethods->xFileControl(id, op, pArg);
19837 }
19838 
19839 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
19840  int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
19841  return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
19842 }
19843 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
19844  return id->pMethods->xDeviceCharacteristics(id);
19845 }
19846 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
19847  return id->pMethods->xShmLock(id, offset, n, flags);
19848 }
19849 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
19850  id->pMethods->xShmBarrier(id);
19851 }
19852 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
19853  return id->pMethods->xShmUnmap(id, deleteFlag);
19854 }
19855 SQLITE_PRIVATE int sqlite3OsShmMap(
19856  sqlite3_file *id, /* Database file handle */
19857  int iPage,
19858  int pgsz,
19859  int bExtend, /* True to extend file if necessary */
19860  void volatile **pp /* OUT: Pointer to mapping */
19861 ){
19862  DO_OS_MALLOC_TEST(id);
19863  return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
19864 }
19865 
19866 #if SQLITE_MAX_MMAP_SIZE>0
19867 /* The real implementation of xFetch and xUnfetch */
19868 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
19869  DO_OS_MALLOC_TEST(id);
19870  return id->pMethods->xFetch(id, iOff, iAmt, pp);
19871 }
19872 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
19873  return id->pMethods->xUnfetch(id, iOff, p);
19874 }
19875 #else
19876 /* No-op stubs to use when memory-mapped I/O is disabled */
19877 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
19878  *pp = 0;
19879  return SQLITE_OK;
19880 }
19881 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
19882  return SQLITE_OK;
19883 }
19884 #endif
19885 
19886 /*
19887 ** The next group of routines are convenience wrappers around the
19888 ** VFS methods.
19889 */
19890 SQLITE_PRIVATE int sqlite3OsOpen(
19891  sqlite3_vfs *pVfs,
19892  const char *zPath,
19893  sqlite3_file *pFile,
19894  int flags,
19895  int *pFlagsOut
19896 ){
19897  int rc;
19898  DO_OS_MALLOC_TEST(0);
19899  /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
19900  ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
19901  ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
19902  ** reaching the VFS. */
19903  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
19904  assert( rc==SQLITE_OK || pFile->pMethods==0 );
19905  return rc;
19906 }
19907 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
19908  DO_OS_MALLOC_TEST(0);
19909  assert( dirSync==0 || dirSync==1 );
19910  return pVfs->xDelete(pVfs, zPath, dirSync);
19911 }
19912 SQLITE_PRIVATE int sqlite3OsAccess(
19913  sqlite3_vfs *pVfs,
19914  const char *zPath,
19915  int flags,
19916  int *pResOut
19917 ){
19918  DO_OS_MALLOC_TEST(0);
19919  return pVfs->xAccess(pVfs, zPath, flags, pResOut);
19920 }
19921 SQLITE_PRIVATE int sqlite3OsFullPathname(
19922  sqlite3_vfs *pVfs,
19923  const char *zPath,
19924  int nPathOut,
19925  char *zPathOut
19926 ){
19927  DO_OS_MALLOC_TEST(0);
19928  zPathOut[0] = 0;
19929  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
19930 }
19931 #ifndef SQLITE_OMIT_LOAD_EXTENSION
19932 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
19933  return pVfs->xDlOpen(pVfs, zPath);
19934 }
19935 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
19936  pVfs->xDlError(pVfs, nByte, zBufOut);
19937 }
19938 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
19939  return pVfs->xDlSym(pVfs, pHdle, zSym);
19940 }
19941 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
19942  pVfs->xDlClose(pVfs, pHandle);
19943 }
19944 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
19945 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
19946  return pVfs->xRandomness(pVfs, nByte, zBufOut);
19947 }
19948 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
19949  return pVfs->xSleep(pVfs, nMicro);
19950 }
19951 SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
19952  return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
19953 }
19954 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
19955  int rc;
19956  /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
19957  ** method to get the current date and time if that method is available
19958  ** (if iVersion is 2 or greater and the function pointer is not NULL) and
19959  ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
19960  ** unavailable.
19961  */
19962  if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
19963  rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
19964  }else{
19965  double r;
19966  rc = pVfs->xCurrentTime(pVfs, &r);
19967  *pTimeOut = (sqlite3_int64)(r*86400000.0);
19968  }
19969  return rc;
19970 }
19971 
19972 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
19973  sqlite3_vfs *pVfs,
19974  const char *zFile,
19975  sqlite3_file **ppFile,
19976  int flags,
19977  int *pOutFlags
19978 ){
19979  int rc;
19980  sqlite3_file *pFile;
19981  pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
19982  if( pFile ){
19983  rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
19984  if( rc!=SQLITE_OK ){
19985  sqlite3_free(pFile);
19986  }else{
19987  *ppFile = pFile;
19988  }
19989  }else{
19990  rc = SQLITE_NOMEM_BKPT;
19991  }
19992  return rc;
19993 }
19994 SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
19995  assert( pFile );
19996  sqlite3OsClose(pFile);
19997  sqlite3_free(pFile);
19998 }
19999 
20000 /*
20001 ** This function is a wrapper around the OS specific implementation of
20002 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
20003 ** ability to simulate a malloc failure, so that the handling of an
20004 ** error in sqlite3_os_init() by the upper layers can be tested.
20005 */
20006 SQLITE_PRIVATE int sqlite3OsInit(void){
20007  void *p = sqlite3_malloc(10);
20008  if( p==0 ) return SQLITE_NOMEM_BKPT;
20009  sqlite3_free(p);
20010  return sqlite3_os_init();
20011 }
20012 
20013 /*
20014 ** The list of all registered VFS implementations.
20015 */
20016 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
20017 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
20018 
20019 /*
20020 ** Locate a VFS by name. If no name is given, simply return the
20021 ** first VFS on the list.
20022 */
20023 SQLITE_API sqlite3_vfs *SQLITE_STDCALL sqlite3_vfs_find(const char *zVfs){
20024  sqlite3_vfs *pVfs = 0;
20025 #if SQLITE_THREADSAFE
20026  sqlite3_mutex *mutex;
20027 #endif
20028 #ifndef SQLITE_OMIT_AUTOINIT
20029  int rc = sqlite3_initialize();
20030  if( rc ) return 0;
20031 #endif
20032 #if SQLITE_THREADSAFE
20033  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
20034 #endif
20035  sqlite3_mutex_enter(mutex);
20036  for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
20037  if( zVfs==0 ) break;
20038  if( strcmp(zVfs, pVfs->zName)==0 ) break;
20039  }
20040  sqlite3_mutex_leave(mutex);
20041  return pVfs;
20042 }
20043 
20044 /*
20045 ** Unlink a VFS from the linked list
20046 */
20047 static void vfsUnlink(sqlite3_vfs *pVfs){
20048  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
20049  if( pVfs==0 ){
20050  /* No-op */
20051  }else if( vfsList==pVfs ){
20052  vfsList = pVfs->pNext;
20053  }else if( vfsList ){
20054  sqlite3_vfs *p = vfsList;
20055  while( p->pNext && p->pNext!=pVfs ){
20056  p = p->pNext;
20057  }
20058  if( p->pNext==pVfs ){
20059  p->pNext = pVfs->pNext;
20060  }
20061  }
20062 }
20063 
20064 /*
20065 ** Register a VFS with the system. It is harmless to register the same
20066 ** VFS multiple times. The new VFS becomes the default if makeDflt is
20067 ** true.
20068 */
20069 SQLITE_API int SQLITE_STDCALL sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
20070  MUTEX_LOGIC(sqlite3_mutex *mutex;)
20071 #ifndef SQLITE_OMIT_AUTOINIT
20072  int rc = sqlite3_initialize();
20073  if( rc ) return rc;
20074 #endif
20075 #ifdef SQLITE_ENABLE_API_ARMOR
20076  if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
20077 #endif
20078 
20079  MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
20080  sqlite3_mutex_enter(mutex);
20081  vfsUnlink(pVfs);
20082  if( makeDflt || vfsList==0 ){
20083  pVfs->pNext = vfsList;
20084  vfsList = pVfs;
20085  }else{
20086  pVfs->pNext = vfsList->pNext;
20087  vfsList->pNext = pVfs;
20088  }
20089  assert(vfsList);
20090  sqlite3_mutex_leave(mutex);
20091  return SQLITE_OK;
20092 }
20093 
20094 /*
20095 ** Unregister a VFS so that it is no longer accessible.
20096 */
20097 SQLITE_API int SQLITE_STDCALL sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
20098 #if SQLITE_THREADSAFE
20099  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
20100 #endif
20101  sqlite3_mutex_enter(mutex);
20102  vfsUnlink(pVfs);
20103  sqlite3_mutex_leave(mutex);
20104  return SQLITE_OK;
20105 }
20106 
20107 /************** End of os.c **************************************************/
20108 /************** Begin file fault.c *******************************************/
20109 /*
20110 ** 2008 Jan 22
20111 **
20112 ** The author disclaims copyright to this source code. In place of
20113 ** a legal notice, here is a blessing:
20114 **
20115 ** May you do good and not evil.
20116 ** May you find forgiveness for yourself and forgive others.
20117 ** May you share freely, never taking more than you give.
20118 **
20119 *************************************************************************
20120 **
20121 ** This file contains code to support the concept of "benign"
20122 ** malloc failures (when the xMalloc() or xRealloc() method of the
20123 ** sqlite3_mem_methods structure fails to allocate a block of memory
20124 ** and returns 0).
20125 **
20126 ** Most malloc failures are non-benign. After they occur, SQLite
20127 ** abandons the current operation and returns an error code (usually
20128 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
20129 ** fatal. For example, if a malloc fails while resizing a hash table, this
20130 ** is completely recoverable simply by not carrying out the resize. The
20131 ** hash table will continue to function normally. So a malloc failure
20132 ** during a hash table resize is a benign fault.
20133 */
20134 
20135 /* #include "sqliteInt.h" */
20136 
20137 #ifndef SQLITE_OMIT_BUILTIN_TEST
20138 
20139 /*
20140 ** Global variables.
20141 */
20142 typedef struct BenignMallocHooks BenignMallocHooks;
20143 static SQLITE_WSD struct BenignMallocHooks {
20144  void (*xBenignBegin)(void);
20145  void (*xBenignEnd)(void);
20146 } sqlite3Hooks = { 0, 0 };
20147 
20148 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
20149 ** structure. If writable static data is unsupported on the target,
20150 ** we have to locate the state vector at run-time. In the more common
20151 ** case where writable static data is supported, wsdHooks can refer directly
20152 ** to the "sqlite3Hooks" state vector declared above.
20153 */
20154 #ifdef SQLITE_OMIT_WSD
20155 # define wsdHooksInit \
20156  BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
20157 # define wsdHooks x[0]
20158 #else
20159 # define wsdHooksInit
20160 # define wsdHooks sqlite3Hooks
20161 #endif
20162 
20163 
20164 /*
20165 ** Register hooks to call when sqlite3BeginBenignMalloc() and
20166 ** sqlite3EndBenignMalloc() are called, respectively.
20167 */
20168 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
20169  void (*xBenignBegin)(void),
20170  void (*xBenignEnd)(void)
20171 ){
20172  wsdHooksInit;
20173  wsdHooks.xBenignBegin = xBenignBegin;
20174  wsdHooks.xBenignEnd = xBenignEnd;
20175 }
20176 
20177 /*
20178 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
20179 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
20180 ** indicates that subsequent malloc failures are non-benign.
20181 */
20182 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
20183  wsdHooksInit;
20184  if( wsdHooks.xBenignBegin ){
20185  wsdHooks.xBenignBegin();
20186  }
20187 }
20188 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
20189  wsdHooksInit;
20190  if( wsdHooks.xBenignEnd ){
20191  wsdHooks.xBenignEnd();
20192  }
20193 }
20194 
20195 #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
20196 
20197 /************** End of fault.c ***********************************************/
20198 /************** Begin file mem0.c ********************************************/
20199 /*
20200 ** 2008 October 28
20201 **
20202 ** The author disclaims copyright to this source code. In place of
20203 ** a legal notice, here is a blessing:
20204 **
20205 ** May you do good and not evil.
20206 ** May you find forgiveness for yourself and forgive others.
20207 ** May you share freely, never taking more than you give.
20208 **
20209 *************************************************************************
20210 **
20211 ** This file contains a no-op memory allocation drivers for use when
20212 ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
20213 ** here always fail. SQLite will not operate with these drivers. These
20214 ** are merely placeholders. Real drivers must be substituted using
20215 ** sqlite3_config() before SQLite will operate.
20216 */
20217 /* #include "sqliteInt.h" */
20218 
20219 /*
20220 ** This version of the memory allocator is the default. It is
20221 ** used when no other memory allocator is specified using compile-time
20222 ** macros.
20223 */
20224 #ifdef SQLITE_ZERO_MALLOC
20225 
20226 /*
20227 ** No-op versions of all memory allocation routines
20228 */
20229 static void *sqlite3MemMalloc(int nByte){ return 0; }
20230 static void sqlite3MemFree(void *pPrior){ return; }
20231 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
20232 static int sqlite3MemSize(void *pPrior){ return 0; }
20233 static int sqlite3MemRoundup(int n){ return n; }
20234 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
20235 static void sqlite3MemShutdown(void *NotUsed){ return; }
20236 
20237 /*
20238 ** This routine is the only routine in this file with external linkage.
20239 **
20240 ** Populate the low-level memory allocation function pointers in
20241 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
20242 */
20243 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
20244  static const sqlite3_mem_methods defaultMethods = {
20245  sqlite3MemMalloc,
20246  sqlite3MemFree,
20247  sqlite3MemRealloc,
20248  sqlite3MemSize,
20249  sqlite3MemRoundup,
20250  sqlite3MemInit,
20251  sqlite3MemShutdown,
20252  0
20253  };
20254  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
20255 }
20256 
20257 #endif /* SQLITE_ZERO_MALLOC */
20258 
20259 /************** End of mem0.c ************************************************/
20260 /************** Begin file mem1.c ********************************************/
20261 /*
20262 ** 2007 August 14
20263 **
20264 ** The author disclaims copyright to this source code. In place of
20265 ** a legal notice, here is a blessing:
20266 **
20267 ** May you do good and not evil.
20268 ** May you find forgiveness for yourself and forgive others.
20269 ** May you share freely, never taking more than you give.
20270 **
20271 *************************************************************************
20272 **
20273 ** This file contains low-level memory allocation drivers for when
20274 ** SQLite will use the standard C-library malloc/realloc/free interface
20275 ** to obtain the memory it needs.
20276 **
20277 ** This file contains implementations of the low-level memory allocation
20278 ** routines specified in the sqlite3_mem_methods object. The content of
20279 ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
20280 ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
20281 ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
20282 ** default configuration is to use memory allocation routines in this
20283 ** file.
20284 **
20285 ** C-preprocessor macro summary:
20286 **
20287 ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
20288 ** the malloc_usable_size() interface exists
20289 ** on the target platform. Or, this symbol
20290 ** can be set manually, if desired.
20291 ** If an equivalent interface exists by
20292 ** a different name, using a separate -D
20293 ** option to rename it.
20294 **
20295 ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
20296 ** memory allocator. Set this symbol to enable
20297 ** building on older macs.
20298 **
20299 ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
20300 ** _msize() on windows systems. This might
20301 ** be necessary when compiling for Delphi,
20302 ** for example.
20303 */
20304 /* #include "sqliteInt.h" */
20305 
20306 /*
20307 ** This version of the memory allocator is the default. It is
20308 ** used when no other memory allocator is specified using compile-time
20309 ** macros.
20310 */
20311 #ifdef SQLITE_SYSTEM_MALLOC
20312 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
20313 
20314 /*
20315 ** Use the zone allocator available on apple products unless the
20316 ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
20317 */
20318 #include <sys/sysctl.h>
20319 #include <malloc/malloc.h>
20320 #include <libkern/OSAtomic.h>
20321 static malloc_zone_t* _sqliteZone_;
20322 #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
20323 #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
20324 #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
20325 #define SQLITE_MALLOCSIZE(x) \
20326  (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
20327 
20328 #else /* if not __APPLE__ */
20329 
20330 /*
20331 ** Use standard C library malloc and free on non-Apple systems.
20332 ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
20333 */
20334 #define SQLITE_MALLOC(x) malloc(x)
20335 #define SQLITE_FREE(x) free(x)
20336 #define SQLITE_REALLOC(x,y) realloc((x),(y))
20337 
20338 /*
20339 ** The malloc.h header file is needed for malloc_usable_size() function
20340 ** on some systems (e.g. Linux).
20341 */
20342 #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
20343 # define SQLITE_USE_MALLOC_H 1
20344 # define SQLITE_USE_MALLOC_USABLE_SIZE 1
20345 /*
20346 ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
20347 ** use of _msize() is automatic, but can be disabled by compiling with
20348 ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
20349 ** the malloc.h header file.
20350 */
20351 #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
20352 # define SQLITE_USE_MALLOC_H
20353 # define SQLITE_USE_MSIZE
20354 #endif
20355 
20356 /*
20357 ** Include the malloc.h header file, if necessary. Also set define macro
20358 ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
20359 ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
20360 ** The memory size function can always be overridden manually by defining
20361 ** the macro SQLITE_MALLOCSIZE to the desired function name.
20362 */
20363 #if defined(SQLITE_USE_MALLOC_H)
20364 # include <malloc.h>
20365 # if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
20366 # if !defined(SQLITE_MALLOCSIZE)
20367 # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
20368 # endif
20369 # elif defined(SQLITE_USE_MSIZE)
20370 # if !defined(SQLITE_MALLOCSIZE)
20371 # define SQLITE_MALLOCSIZE _msize
20372 # endif
20373 # endif
20374 #endif /* defined(SQLITE_USE_MALLOC_H) */
20375 
20376 #endif /* __APPLE__ or not __APPLE__ */
20377 
20378 /*
20379 ** Like malloc(), but remember the size of the allocation
20380 ** so that we can find it later using sqlite3MemSize().
20381 **
20382 ** For this low-level routine, we are guaranteed that nByte>0 because
20383 ** cases of nByte<=0 will be intercepted and dealt with by higher level
20384 ** routines.
20385 */
20386 static void *sqlite3MemMalloc(int nByte){
20387 #ifdef SQLITE_MALLOCSIZE
20388  void *p = SQLITE_MALLOC( nByte );
20389  if( p==0 ){
20390  testcase( sqlite3GlobalConfig.xLog!=0 );
20391  sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
20392  }
20393  return p;
20394 #else
20395  sqlite3_int64 *p;
20396  assert( nByte>0 );
20397  nByte = ROUND8(nByte);
20398  p = SQLITE_MALLOC( nByte+8 );
20399  if( p ){
20400  p[0] = nByte;
20401  p++;
20402  }else{
20403  testcase( sqlite3GlobalConfig.xLog!=0 );
20404  sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
20405  }
20406  return (void *)p;
20407 #endif
20408 }
20409 
20410 /*
20411 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
20412 ** or sqlite3MemRealloc().
20413 **
20414 ** For this low-level routine, we already know that pPrior!=0 since
20415 ** cases where pPrior==0 will have been intecepted and dealt with
20416 ** by higher-level routines.
20417 */
20418 static void sqlite3MemFree(void *pPrior){
20419 #ifdef SQLITE_MALLOCSIZE
20420  SQLITE_FREE(pPrior);
20421 #else
20422  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
20423  assert( pPrior!=0 );
20424  p--;
20425  SQLITE_FREE(p);
20426 #endif
20427 }
20428 
20429 /*
20430 ** Report the allocated size of a prior return from xMalloc()
20431 ** or xRealloc().
20432 */
20433 static int sqlite3MemSize(void *pPrior){
20434 #ifdef SQLITE_MALLOCSIZE
20435  assert( pPrior!=0 );
20436  return (int)SQLITE_MALLOCSIZE(pPrior);
20437 #else
20438  sqlite3_int64 *p;
20439  assert( pPrior!=0 );
20440  p = (sqlite3_int64*)pPrior;
20441  p--;
20442  return (int)p[0];
20443 #endif
20444 }
20445 
20446 /*
20447 ** Like realloc(). Resize an allocation previously obtained from
20448 ** sqlite3MemMalloc().
20449 **
20450 ** For this low-level interface, we know that pPrior!=0. Cases where
20451 ** pPrior==0 while have been intercepted by higher-level routine and
20452 ** redirected to xMalloc. Similarly, we know that nByte>0 because
20453 ** cases where nByte<=0 will have been intercepted by higher-level
20454 ** routines and redirected to xFree.
20455 */
20456 static void *sqlite3MemRealloc(void *pPrior, int nByte){
20457 #ifdef SQLITE_MALLOCSIZE
20458  void *p = SQLITE_REALLOC(pPrior, nByte);
20459  if( p==0 ){
20460  testcase( sqlite3GlobalConfig.xLog!=0 );
20461  sqlite3_log(SQLITE_NOMEM,
20462  "failed memory resize %u to %u bytes",
20463  SQLITE_MALLOCSIZE(pPrior), nByte);
20464  }
20465  return p;
20466 #else
20467  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
20468  assert( pPrior!=0 && nByte>0 );
20469  assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
20470  p--;
20471  p = SQLITE_REALLOC(p, nByte+8 );
20472  if( p ){
20473  p[0] = nByte;
20474  p++;
20475  }else{
20476  testcase( sqlite3GlobalConfig.xLog!=0 );
20477  sqlite3_log(SQLITE_NOMEM,
20478  "failed memory resize %u to %u bytes",
20479  sqlite3MemSize(pPrior), nByte);
20480  }
20481  return (void*)p;
20482 #endif
20483 }
20484 
20485 /*
20486 ** Round up a request size to the next valid allocation size.
20487 */
20488 static int sqlite3MemRoundup(int n){
20489  return ROUND8(n);
20490 }
20491 
20492 /*
20493 ** Initialize this module.
20494 */
20495 static int sqlite3MemInit(void *NotUsed){
20496 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
20497  int cpuCount;
20498  size_t len;
20499  if( _sqliteZone_ ){
20500  return SQLITE_OK;
20501  }
20502  len = sizeof(cpuCount);
20503  /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
20504  sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
20505  if( cpuCount>1 ){
20506  /* defer MT decisions to system malloc */
20507  _sqliteZone_ = malloc_default_zone();
20508  }else{
20509  /* only 1 core, use our own zone to contention over global locks,
20510  ** e.g. we have our own dedicated locks */
20511  bool success;
20512  malloc_zone_t* newzone = malloc_create_zone(4096, 0);
20513  malloc_set_zone_name(newzone, "Sqlite_Heap");
20514  do{
20515  success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
20516  (void * volatile *)&_sqliteZone_);
20517  }while(!_sqliteZone_);
20518  if( !success ){
20519  /* somebody registered a zone first */
20520  malloc_destroy_zone(newzone);
20521  }
20522  }
20523 #endif
20524  UNUSED_PARAMETER(NotUsed);
20525  return SQLITE_OK;
20526 }
20527 
20528 /*
20529 ** Deinitialize this module.
20530 */
20531 static void sqlite3MemShutdown(void *NotUsed){
20532  UNUSED_PARAMETER(NotUsed);
20533  return;
20534 }
20535 
20536 /*
20537 ** This routine is the only routine in this file with external linkage.
20538 **
20539 ** Populate the low-level memory allocation function pointers in
20540 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
20541 */
20542 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
20543  static const sqlite3_mem_methods defaultMethods = {
20544  sqlite3MemMalloc,
20545  sqlite3MemFree,
20546  sqlite3MemRealloc,
20547  sqlite3MemSize,
20548  sqlite3MemRoundup,
20549  sqlite3MemInit,
20550  sqlite3MemShutdown,
20551  0
20552  };
20553  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
20554 }
20555 
20556 #endif /* SQLITE_SYSTEM_MALLOC */
20557 
20558 /************** End of mem1.c ************************************************/
20559 /************** Begin file mem2.c ********************************************/
20560 /*
20561 ** 2007 August 15
20562 **
20563 ** The author disclaims copyright to this source code. In place of
20564 ** a legal notice, here is a blessing:
20565 **
20566 ** May you do good and not evil.
20567 ** May you find forgiveness for yourself and forgive others.
20568 ** May you share freely, never taking more than you give.
20569 **
20570 *************************************************************************
20571 **
20572 ** This file contains low-level memory allocation drivers for when
20573 ** SQLite will use the standard C-library malloc/realloc/free interface
20574 ** to obtain the memory it needs while adding lots of additional debugging
20575 ** information to each allocation in order to help detect and fix memory
20576 ** leaks and memory usage errors.
20577 **
20578 ** This file contains implementations of the low-level memory allocation
20579 ** routines specified in the sqlite3_mem_methods object.
20580 */
20581 /* #include "sqliteInt.h" */
20582 
20583 /*
20584 ** This version of the memory allocator is used only if the
20585 ** SQLITE_MEMDEBUG macro is defined
20586 */
20587 #ifdef SQLITE_MEMDEBUG
20588 
20589 /*
20590 ** The backtrace functionality is only available with GLIBC
20591 */
20592 #ifdef __GLIBC__
20593  extern int backtrace(void**,int);
20594  extern void backtrace_symbols_fd(void*const*,int,int);
20595 #else
20596 # define backtrace(A,B) 1
20597 # define backtrace_symbols_fd(A,B,C)
20598 #endif
20599 /* #include <stdio.h> */
20600 
20601 /*
20602 ** Each memory allocation looks like this:
20603 **
20604 ** ------------------------------------------------------------------------
20605 ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
20606 ** ------------------------------------------------------------------------
20607 **
20608 ** The application code sees only a pointer to the allocation. We have
20609 ** to back up from the allocation pointer to find the MemBlockHdr. The
20610 ** MemBlockHdr tells us the size of the allocation and the number of
20611 ** backtrace pointers. There is also a guard word at the end of the
20612 ** MemBlockHdr.
20613 */
20614 struct MemBlockHdr {
20615  i64 iSize; /* Size of this allocation */
20616  struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
20617  char nBacktrace; /* Number of backtraces on this alloc */
20618  char nBacktraceSlots; /* Available backtrace slots */
20619  u8 nTitle; /* Bytes of title; includes '\0' */
20620  u8 eType; /* Allocation type code */
20621  int iForeGuard; /* Guard word for sanity */
20622 };
20623 
20624 /*
20625 ** Guard words
20626 */
20627 #define FOREGUARD 0x80F5E153
20628 #define REARGUARD 0xE4676B53
20629 
20630 /*
20631 ** Number of malloc size increments to track.
20632 */
20633 #define NCSIZE 1000
20634 
20635 /*
20636 ** All of the static variables used by this module are collected
20637 ** into a single structure named "mem". This is to keep the
20638 ** static variables organized and to reduce namespace pollution
20639 ** when this module is combined with other in the amalgamation.
20640 */
20641 static struct {
20642 
20643  /*
20644  ** Mutex to control access to the memory allocation subsystem.
20645  */
20646  sqlite3_mutex *mutex;
20647 
20648  /*
20649  ** Head and tail of a linked list of all outstanding allocations
20650  */
20651  struct MemBlockHdr *pFirst;
20652  struct MemBlockHdr *pLast;
20653 
20654  /*
20655  ** The number of levels of backtrace to save in new allocations.
20656  */
20657  int nBacktrace;
20658  void (*xBacktrace)(int, int, void **);
20659 
20660  /*
20661  ** Title text to insert in front of each block
20662  */
20663  int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
20664  char zTitle[100]; /* The title text */
20665 
20666  /*
20667  ** sqlite3MallocDisallow() increments the following counter.
20668  ** sqlite3MallocAllow() decrements it.
20669  */
20670  int disallow; /* Do not allow memory allocation */
20671 
20672  /*
20673  ** Gather statistics on the sizes of memory allocations.
20674  ** nAlloc[i] is the number of allocation attempts of i*8
20675  ** bytes. i==NCSIZE is the number of allocation attempts for
20676  ** sizes more than NCSIZE*8 bytes.
20677  */
20678  int nAlloc[NCSIZE]; /* Total number of allocations */
20679  int nCurrent[NCSIZE]; /* Current number of allocations */
20680  int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
20681 
20682 } mem;
20683 
20684 
20685 /*
20686 ** Adjust memory usage statistics
20687 */
20688 static void adjustStats(int iSize, int increment){
20689  int i = ROUND8(iSize)/8;
20690  if( i>NCSIZE-1 ){
20691  i = NCSIZE - 1;
20692  }
20693  if( increment>0 ){
20694  mem.nAlloc[i]++;
20695  mem.nCurrent[i]++;
20696  if( mem.nCurrent[i]>mem.mxCurrent[i] ){
20697  mem.mxCurrent[i] = mem.nCurrent[i];
20698  }
20699  }else{
20700  mem.nCurrent[i]--;
20701  assert( mem.nCurrent[i]>=0 );
20702  }
20703 }
20704 
20705 /*
20706 ** Given an allocation, find the MemBlockHdr for that allocation.
20707 **
20708 ** This routine checks the guards at either end of the allocation and
20709 ** if they are incorrect it asserts.
20710 */
20711 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
20712  struct MemBlockHdr *p;
20713  int *pInt;
20714  u8 *pU8;
20715  int nReserve;
20716 
20717  p = (struct MemBlockHdr*)pAllocation;
20718  p--;
20719  assert( p->iForeGuard==(int)FOREGUARD );
20720  nReserve = ROUND8(p->iSize);
20721  pInt = (int*)pAllocation;
20722  pU8 = (u8*)pAllocation;
20723  assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
20724  /* This checks any of the "extra" bytes allocated due
20725  ** to rounding up to an 8 byte boundary to ensure
20726  ** they haven't been overwritten.
20727  */
20728  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
20729  return p;
20730 }
20731 
20732 /*
20733 ** Return the number of bytes currently allocated at address p.
20734 */
20735 static int sqlite3MemSize(void *p){
20736  struct MemBlockHdr *pHdr;
20737  if( !p ){
20738  return 0;
20739  }
20740  pHdr = sqlite3MemsysGetHeader(p);
20741  return (int)pHdr->iSize;
20742 }
20743 
20744 /*
20745 ** Initialize the memory allocation subsystem.
20746 */
20747 static int sqlite3MemInit(void *NotUsed){
20748  UNUSED_PARAMETER(NotUsed);
20749  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
20750  if( !sqlite3GlobalConfig.bMemstat ){
20751  /* If memory status is enabled, then the malloc.c wrapper will already
20752  ** hold the STATIC_MEM mutex when the routines here are invoked. */
20753  mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
20754  }
20755  return SQLITE_OK;
20756 }
20757 
20758 /*
20759 ** Deinitialize the memory allocation subsystem.
20760 */
20761 static void sqlite3MemShutdown(void *NotUsed){
20762  UNUSED_PARAMETER(NotUsed);
20763  mem.mutex = 0;
20764 }
20765 
20766 /*
20767 ** Round up a request size to the next valid allocation size.
20768 */
20769 static int sqlite3MemRoundup(int n){
20770  return ROUND8(n);
20771 }
20772 
20773 /*
20774 ** Fill a buffer with pseudo-random bytes. This is used to preset
20775 ** the content of a new memory allocation to unpredictable values and
20776 ** to clear the content of a freed allocation to unpredictable values.
20777 */
20778 static void randomFill(char *pBuf, int nByte){
20779  unsigned int x, y, r;
20780  x = SQLITE_PTR_TO_INT(pBuf);
20781  y = nByte | 1;
20782  while( nByte >= 4 ){
20783  x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
20784  y = y*1103515245 + 12345;
20785  r = x ^ y;
20786  *(int*)pBuf = r;
20787  pBuf += 4;
20788  nByte -= 4;
20789  }
20790  while( nByte-- > 0 ){
20791  x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
20792  y = y*1103515245 + 12345;
20793  r = x ^ y;
20794  *(pBuf++) = r & 0xff;
20795  }
20796 }
20797 
20798 /*
20799 ** Allocate nByte bytes of memory.
20800 */
20801 static void *sqlite3MemMalloc(int nByte){
20802  struct MemBlockHdr *pHdr;
20803  void **pBt;
20804  char *z;
20805  int *pInt;
20806  void *p = 0;
20807  int totalSize;
20808  int nReserve;
20809  sqlite3_mutex_enter(mem.mutex);
20810  assert( mem.disallow==0 );
20811  nReserve = ROUND8(nByte);
20812  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
20813  mem.nBacktrace*sizeof(void*) + mem.nTitle;
20814  p = malloc(totalSize);
20815  if( p ){
20816  z = p;
20817  pBt = (void**)&z[mem.nTitle];
20818  pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
20819  pHdr->pNext = 0;
20820  pHdr->pPrev = mem.pLast;
20821  if( mem.pLast ){
20822  mem.pLast->pNext = pHdr;
20823  }else{
20824  mem.pFirst = pHdr;
20825  }
20826  mem.pLast = pHdr;
20827  pHdr->iForeGuard = FOREGUARD;
20828  pHdr->eType = MEMTYPE_HEAP;
20829  pHdr->nBacktraceSlots = mem.nBacktrace;
20830  pHdr->nTitle = mem.nTitle;
20831  if( mem.nBacktrace ){
20832  void *aAddr[40];
20833  pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
20834  memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
20835  assert(pBt[0]);
20836  if( mem.xBacktrace ){
20837  mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
20838  }
20839  }else{
20840  pHdr->nBacktrace = 0;
20841  }
20842  if( mem.nTitle ){
20843  memcpy(z, mem.zTitle, mem.nTitle);
20844  }
20845  pHdr->iSize = nByte;
20846  adjustStats(nByte, +1);
20847  pInt = (int*)&pHdr[1];
20848  pInt[nReserve/sizeof(int)] = REARGUARD;
20849  randomFill((char*)pInt, nByte);
20850  memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
20851  p = (void*)pInt;
20852  }
20853  sqlite3_mutex_leave(mem.mutex);
20854  return p;
20855 }
20856 
20857 /*
20858 ** Free memory.
20859 */
20860 static void sqlite3MemFree(void *pPrior){
20861  struct MemBlockHdr *pHdr;
20862  void **pBt;
20863  char *z;
20864  assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
20865  || mem.mutex!=0 );
20866  pHdr = sqlite3MemsysGetHeader(pPrior);
20867  pBt = (void**)pHdr;
20868  pBt -= pHdr->nBacktraceSlots;
20869  sqlite3_mutex_enter(mem.mutex);
20870  if( pHdr->pPrev ){
20871  assert( pHdr->pPrev->pNext==pHdr );
20872  pHdr->pPrev->pNext = pHdr->pNext;
20873  }else{
20874  assert( mem.pFirst==pHdr );
20875  mem.pFirst = pHdr->pNext;
20876  }
20877  if( pHdr->pNext ){
20878  assert( pHdr->pNext->pPrev==pHdr );
20879  pHdr->pNext->pPrev = pHdr->pPrev;
20880  }else{
20881  assert( mem.pLast==pHdr );
20882  mem.pLast = pHdr->pPrev;
20883  }
20884  z = (char*)pBt;
20885  z -= pHdr->nTitle;
20886  adjustStats((int)pHdr->iSize, -1);
20887  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
20888  (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
20889  free(z);
20890  sqlite3_mutex_leave(mem.mutex);
20891 }
20892 
20893 /*
20894 ** Change the size of an existing memory allocation.
20895 **
20896 ** For this debugging implementation, we *always* make a copy of the
20897 ** allocation into a new place in memory. In this way, if the
20898 ** higher level code is using pointer to the old allocation, it is
20899 ** much more likely to break and we are much more liking to find
20900 ** the error.
20901 */
20902 static void *sqlite3MemRealloc(void *pPrior, int nByte){
20903  struct MemBlockHdr *pOldHdr;
20904  void *pNew;
20905  assert( mem.disallow==0 );
20906  assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
20907  pOldHdr = sqlite3MemsysGetHeader(pPrior);
20908  pNew = sqlite3MemMalloc(nByte);
20909  if( pNew ){
20910  memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
20911  if( nByte>pOldHdr->iSize ){
20912  randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
20913  }
20914  sqlite3MemFree(pPrior);
20915  }
20916  return pNew;
20917 }
20918 
20919 /*
20920 ** Populate the low-level memory allocation function pointers in
20921 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
20922 */
20923 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
20924  static const sqlite3_mem_methods defaultMethods = {
20925  sqlite3MemMalloc,
20926  sqlite3MemFree,
20927  sqlite3MemRealloc,
20928  sqlite3MemSize,
20929  sqlite3MemRoundup,
20930  sqlite3MemInit,
20931  sqlite3MemShutdown,
20932  0
20933  };
20934  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
20935 }
20936 
20937 /*
20938 ** Set the "type" of an allocation.
20939 */
20940 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
20941  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
20942  struct MemBlockHdr *pHdr;
20943  pHdr = sqlite3MemsysGetHeader(p);
20944  assert( pHdr->iForeGuard==FOREGUARD );
20945  pHdr->eType = eType;
20946  }
20947 }
20948 
20949 /*
20950 ** Return TRUE if the mask of type in eType matches the type of the
20951 ** allocation p. Also return true if p==NULL.
20952 **
20953 ** This routine is designed for use within an assert() statement, to
20954 ** verify the type of an allocation. For example:
20955 **
20956 ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
20957 */
20958 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
20959  int rc = 1;
20960  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
20961  struct MemBlockHdr *pHdr;
20962  pHdr = sqlite3MemsysGetHeader(p);
20963  assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
20964  if( (pHdr->eType&eType)==0 ){
20965  rc = 0;
20966  }
20967  }
20968  return rc;
20969 }
20970 
20971 /*
20972 ** Return TRUE if the mask of type in eType matches no bits of the type of the
20973 ** allocation p. Also return true if p==NULL.
20974 **
20975 ** This routine is designed for use within an assert() statement, to
20976 ** verify the type of an allocation. For example:
20977 **
20978 ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
20979 */
20980 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
20981  int rc = 1;
20982  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
20983  struct MemBlockHdr *pHdr;
20984  pHdr = sqlite3MemsysGetHeader(p);
20985  assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
20986  if( (pHdr->eType&eType)!=0 ){
20987  rc = 0;
20988  }
20989  }
20990  return rc;
20991 }
20992 
20993 /*
20994 ** Set the number of backtrace levels kept for each allocation.
20995 ** A value of zero turns off backtracing. The number is always rounded
20996 ** up to a multiple of 2.
20997 */
20998 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
20999  if( depth<0 ){ depth = 0; }
21000  if( depth>20 ){ depth = 20; }
21001  depth = (depth+1)&0xfe;
21002  mem.nBacktrace = depth;
21003 }
21004 
21005 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
21006  mem.xBacktrace = xBacktrace;
21007 }
21008 
21009 /*
21010 ** Set the title string for subsequent allocations.
21011 */
21012 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
21013  unsigned int n = sqlite3Strlen30(zTitle) + 1;
21014  sqlite3_mutex_enter(mem.mutex);
21015  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
21016  memcpy(mem.zTitle, zTitle, n);
21017  mem.zTitle[n] = 0;
21018  mem.nTitle = ROUND8(n);
21019  sqlite3_mutex_leave(mem.mutex);
21020 }
21021 
21022 SQLITE_PRIVATE void sqlite3MemdebugSync(){
21023  struct MemBlockHdr *pHdr;
21024  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
21025  void **pBt = (void**)pHdr;
21026  pBt -= pHdr->nBacktraceSlots;
21027  mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
21028  }
21029 }
21030 
21031 /*
21032 ** Open the file indicated and write a log of all unfreed memory
21033 ** allocations into that log.
21034 */
21035 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
21036  FILE *out;
21037  struct MemBlockHdr *pHdr;
21038  void **pBt;
21039  int i;
21040  out = fopen(zFilename, "w");
21041  if( out==0 ){
21042  fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
21043  zFilename);
21044  return;
21045  }
21046  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
21047  char *z = (char*)pHdr;
21048  z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
21049  fprintf(out, "**** %lld bytes at %p from %s ****\n",
21050  pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
21051  if( pHdr->nBacktrace ){
21052  fflush(out);
21053  pBt = (void**)pHdr;
21054  pBt -= pHdr->nBacktraceSlots;
21055  backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
21056  fprintf(out, "\n");
21057  }
21058  }
21059  fprintf(out, "COUNTS:\n");
21060  for(i=0; i<NCSIZE-1; i++){
21061  if( mem.nAlloc[i] ){
21062  fprintf(out, " %5d: %10d %10d %10d\n",
21063  i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
21064  }
21065  }
21066  if( mem.nAlloc[NCSIZE-1] ){
21067  fprintf(out, " %5d: %10d %10d %10d\n",
21068  NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
21069  mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
21070  }
21071  fclose(out);
21072 }
21073 
21074 /*
21075 ** Return the number of times sqlite3MemMalloc() has been called.
21076 */
21077 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
21078  int i;
21079  int nTotal = 0;
21080  for(i=0; i<NCSIZE; i++){
21081  nTotal += mem.nAlloc[i];
21082  }
21083  return nTotal;
21084 }
21085 
21086 
21087 #endif /* SQLITE_MEMDEBUG */
21088 
21089 /************** End of mem2.c ************************************************/
21090 /************** Begin file mem3.c ********************************************/
21091 /*
21092 ** 2007 October 14
21093 **
21094 ** The author disclaims copyright to this source code. In place of
21095 ** a legal notice, here is a blessing:
21096 **
21097 ** May you do good and not evil.
21098 ** May you find forgiveness for yourself and forgive others.
21099 ** May you share freely, never taking more than you give.
21100 **
21101 *************************************************************************
21102 ** This file contains the C functions that implement a memory
21103 ** allocation subsystem for use by SQLite.
21104 **
21105 ** This version of the memory allocation subsystem omits all
21106 ** use of malloc(). The SQLite user supplies a block of memory
21107 ** before calling sqlite3_initialize() from which allocations
21108 ** are made and returned by the xMalloc() and xRealloc()
21109 ** implementations. Once sqlite3_initialize() has been called,
21110 ** the amount of memory available to SQLite is fixed and cannot
21111 ** be changed.
21112 **
21113 ** This version of the memory allocation subsystem is included
21114 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
21115 */
21116 /* #include "sqliteInt.h" */
21117 
21118 /*
21119 ** This version of the memory allocator is only built into the library
21120 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
21121 ** mean that the library will use a memory-pool by default, just that
21122 ** it is available. The mempool allocator is activated by calling
21123 ** sqlite3_config().
21124 */
21125 #ifdef SQLITE_ENABLE_MEMSYS3
21126 
21127 /*
21128 ** Maximum size (in Mem3Blocks) of a "small" chunk.
21129 */
21130 #define MX_SMALL 10
21131 
21132 
21133 /*
21134 ** Number of freelist hash slots
21135 */
21136 #define N_HASH 61
21137 
21138 /*
21139 ** A memory allocation (also called a "chunk") consists of two or
21140 ** more blocks where each block is 8 bytes. The first 8 bytes are
21141 ** a header that is not returned to the user.
21142 **
21143 ** A chunk is two or more blocks that is either checked out or
21144 ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
21145 ** size of the allocation in blocks if the allocation is free.
21146 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
21147 ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
21148 ** is true if the previous chunk is checked out and false if the
21149 ** previous chunk is free. The u.hdr.prevSize field is the size of
21150 ** the previous chunk in blocks if the previous chunk is on the
21151 ** freelist. If the previous chunk is checked out, then
21152 ** u.hdr.prevSize can be part of the data for that chunk and should
21153 ** not be read or written.
21154 **
21155 ** We often identify a chunk by its index in mem3.aPool[]. When
21156 ** this is done, the chunk index refers to the second block of
21157 ** the chunk. In this way, the first chunk has an index of 1.
21158 ** A chunk index of 0 means "no such chunk" and is the equivalent
21159 ** of a NULL pointer.
21160 **
21161 ** The second block of free chunks is of the form u.list. The
21162 ** two fields form a double-linked list of chunks of related sizes.
21163 ** Pointers to the head of the list are stored in mem3.aiSmall[]
21164 ** for smaller chunks and mem3.aiHash[] for larger chunks.
21165 **
21166 ** The second block of a chunk is user data if the chunk is checked
21167 ** out. If a chunk is checked out, the user data may extend into
21168 ** the u.hdr.prevSize value of the following chunk.
21169 */
21170 typedef struct Mem3Block Mem3Block;
21171 struct Mem3Block {
21172  union {
21173  struct {
21174  u32 prevSize; /* Size of previous chunk in Mem3Block elements */
21175  u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
21176  } hdr;
21177  struct {
21178  u32 next; /* Index in mem3.aPool[] of next free chunk */
21179  u32 prev; /* Index in mem3.aPool[] of previous free chunk */
21180  } list;
21181  } u;
21182 };
21183 
21184 /*
21185 ** All of the static variables used by this module are collected
21186 ** into a single structure named "mem3". This is to keep the
21187 ** static variables organized and to reduce namespace pollution
21188 ** when this module is combined with other in the amalgamation.
21189 */
21190 static SQLITE_WSD struct Mem3Global {
21191  /*
21192  ** Memory available for allocation. nPool is the size of the array
21193  ** (in Mem3Blocks) pointed to by aPool less 2.
21194  */
21195  u32 nPool;
21196  Mem3Block *aPool;
21197 
21198  /*
21199  ** True if we are evaluating an out-of-memory callback.
21200  */
21201  int alarmBusy;
21202 
21203  /*
21204  ** Mutex to control access to the memory allocation subsystem.
21205  */
21206  sqlite3_mutex *mutex;
21207 
21208  /*
21209  ** The minimum amount of free space that we have seen.
21210  */
21211  u32 mnMaster;
21212 
21213  /*
21214  ** iMaster is the index of the master chunk. Most new allocations
21215  ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
21216  ** of the current master. iMaster is 0 if there is not master chunk.
21217  ** The master chunk is not in either the aiHash[] or aiSmall[].
21218  */
21219  u32 iMaster;
21220  u32 szMaster;
21221 
21222  /*
21223  ** Array of lists of free blocks according to the block size
21224  ** for smaller chunks, or a hash on the block size for larger
21225  ** chunks.
21226  */
21227  u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
21228  u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
21229 } mem3 = { 97535575 };
21230 
21231 #define mem3 GLOBAL(struct Mem3Global, mem3)
21232 
21233 /*
21234 ** Unlink the chunk at mem3.aPool[i] from list it is currently
21235 ** on. *pRoot is the list that i is a member of.
21236 */
21237 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
21238  u32 next = mem3.aPool[i].u.list.next;
21239  u32 prev = mem3.aPool[i].u.list.prev;
21240  assert( sqlite3_mutex_held(mem3.mutex) );
21241  if( prev==0 ){
21242  *pRoot = next;
21243  }else{
21244  mem3.aPool[prev].u.list.next = next;
21245  }
21246  if( next ){
21247  mem3.aPool[next].u.list.prev = prev;
21248  }
21249  mem3.aPool[i].u.list.next = 0;
21250  mem3.aPool[i].u.list.prev = 0;
21251 }
21252 
21253 /*
21254 ** Unlink the chunk at index i from
21255 ** whatever list is currently a member of.
21256 */
21257 static void memsys3Unlink(u32 i){
21258  u32 size, hash;
21259  assert( sqlite3_mutex_held(mem3.mutex) );
21260  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
21261  assert( i>=1 );
21262  size = mem3.aPool[i-1].u.hdr.size4x/4;
21263  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
21264  assert( size>=2 );
21265  if( size <= MX_SMALL ){
21266  memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
21267  }else{
21268  hash = size % N_HASH;
21269  memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
21270  }
21271 }
21272 
21273 /*
21274 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
21275 ** at *pRoot.
21276 */
21277 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
21278  assert( sqlite3_mutex_held(mem3.mutex) );
21279  mem3.aPool[i].u.list.next = *pRoot;
21280  mem3.aPool[i].u.list.prev = 0;
21281  if( *pRoot ){
21282  mem3.aPool[*pRoot].u.list.prev = i;
21283  }
21284  *pRoot = i;
21285 }
21286 
21287 /*
21288 ** Link the chunk at index i into either the appropriate
21289 ** small chunk list, or into the large chunk hash table.
21290 */
21291 static void memsys3Link(u32 i){
21292  u32 size, hash;
21293  assert( sqlite3_mutex_held(mem3.mutex) );
21294  assert( i>=1 );
21295  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
21296  size = mem3.aPool[i-1].u.hdr.size4x/4;
21297  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
21298  assert( size>=2 );
21299  if( size <= MX_SMALL ){
21300  memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
21301  }else{
21302  hash = size % N_HASH;
21303  memsys3LinkIntoList(i, &mem3.aiHash[hash]);
21304  }
21305 }
21306 
21307 /*
21308 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
21309 ** will already be held (obtained by code in malloc.c) if
21310 ** sqlite3GlobalConfig.bMemStat is true.
21311 */
21312 static void memsys3Enter(void){
21313  if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
21314  mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
21315  }
21316  sqlite3_mutex_enter(mem3.mutex);
21317 }
21318 static void memsys3Leave(void){
21319  sqlite3_mutex_leave(mem3.mutex);
21320 }
21321 
21322 /*
21323 ** Called when we are unable to satisfy an allocation of nBytes.
21324 */
21325 static void memsys3OutOfMemory(int nByte){
21326  if( !mem3.alarmBusy ){
21327  mem3.alarmBusy = 1;
21328  assert( sqlite3_mutex_held(mem3.mutex) );
21329  sqlite3_mutex_leave(mem3.mutex);
21330  sqlite3_release_memory(nByte);
21331  sqlite3_mutex_enter(mem3.mutex);
21332  mem3.alarmBusy = 0;
21333  }
21334 }
21335 
21336 
21337 /*
21338 ** Chunk i is a free chunk that has been unlinked. Adjust its
21339 ** size parameters for check-out and return a pointer to the
21340 ** user portion of the chunk.
21341 */
21342 static void *memsys3Checkout(u32 i, u32 nBlock){
21343  u32 x;
21344  assert( sqlite3_mutex_held(mem3.mutex) );
21345  assert( i>=1 );
21346  assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
21347  assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
21348  x = mem3.aPool[i-1].u.hdr.size4x;
21349  mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
21350  mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
21351  mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
21352  return &mem3.aPool[i];
21353 }
21354 
21355 /*
21356 ** Carve a piece off of the end of the mem3.iMaster free chunk.
21357 ** Return a pointer to the new allocation. Or, if the master chunk
21358 ** is not large enough, return 0.
21359 */
21360 static void *memsys3FromMaster(u32 nBlock){
21361  assert( sqlite3_mutex_held(mem3.mutex) );
21362  assert( mem3.szMaster>=nBlock );
21363  if( nBlock>=mem3.szMaster-1 ){
21364  /* Use the entire master */
21365  void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
21366  mem3.iMaster = 0;
21367  mem3.szMaster = 0;
21368  mem3.mnMaster = 0;
21369  return p;
21370  }else{
21371  /* Split the master block. Return the tail. */
21372  u32 newi, x;
21373  newi = mem3.iMaster + mem3.szMaster - nBlock;
21374  assert( newi > mem3.iMaster+1 );
21375  mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
21376  mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
21377  mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
21378  mem3.szMaster -= nBlock;
21379  mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
21380  x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
21381  mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
21382  if( mem3.szMaster < mem3.mnMaster ){
21383  mem3.mnMaster = mem3.szMaster;
21384  }
21385  return (void*)&mem3.aPool[newi];
21386  }
21387 }
21388 
21389 /*
21390 ** *pRoot is the head of a list of free chunks of the same size
21391 ** or same size hash. In other words, *pRoot is an entry in either
21392 ** mem3.aiSmall[] or mem3.aiHash[].
21393 **
21394 ** This routine examines all entries on the given list and tries
21395 ** to coalesce each entries with adjacent free chunks.
21396 **
21397 ** If it sees a chunk that is larger than mem3.iMaster, it replaces
21398 ** the current mem3.iMaster with the new larger chunk. In order for
21399 ** this mem3.iMaster replacement to work, the master chunk must be
21400 ** linked into the hash tables. That is not the normal state of
21401 ** affairs, of course. The calling routine must link the master
21402 ** chunk before invoking this routine, then must unlink the (possibly
21403 ** changed) master chunk once this routine has finished.
21404 */
21405 static void memsys3Merge(u32 *pRoot){
21406  u32 iNext, prev, size, i, x;
21407 
21408  assert( sqlite3_mutex_held(mem3.mutex) );
21409  for(i=*pRoot; i>0; i=iNext){
21410  iNext = mem3.aPool[i].u.list.next;
21411  size = mem3.aPool[i-1].u.hdr.size4x;
21412  assert( (size&1)==0 );
21413  if( (size&2)==0 ){
21414  memsys3UnlinkFromList(i, pRoot);
21415  assert( i > mem3.aPool[i-1].u.hdr.prevSize );
21416  prev = i - mem3.aPool[i-1].u.hdr.prevSize;
21417  if( prev==iNext ){
21418  iNext = mem3.aPool[prev].u.list.next;
21419  }
21420  memsys3Unlink(prev);
21421  size = i + size/4 - prev;
21422  x = mem3.aPool[prev-1].u.hdr.size4x & 2;
21423  mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
21424  mem3.aPool[prev+size-1].u.hdr.prevSize = size;
21425  memsys3Link(prev);
21426  i = prev;
21427  }else{
21428  size /= 4;
21429  }
21430  if( size>mem3.szMaster ){
21431  mem3.iMaster = i;
21432  mem3.szMaster = size;
21433  }
21434  }
21435 }
21436 
21437 /*
21438 ** Return a block of memory of at least nBytes in size.
21439 ** Return NULL if unable.
21440 **
21441 ** This function assumes that the necessary mutexes, if any, are
21442 ** already held by the caller. Hence "Unsafe".
21443 */
21444 static void *memsys3MallocUnsafe(int nByte){
21445  u32 i;
21446  u32 nBlock;
21447  u32 toFree;
21448 
21449  assert( sqlite3_mutex_held(mem3.mutex) );
21450  assert( sizeof(Mem3Block)==8 );
21451  if( nByte<=12 ){
21452  nBlock = 2;
21453  }else{
21454  nBlock = (nByte + 11)/8;
21455  }
21456  assert( nBlock>=2 );
21457 
21458  /* STEP 1:
21459  ** Look for an entry of the correct size in either the small
21460  ** chunk table or in the large chunk hash table. This is
21461  ** successful most of the time (about 9 times out of 10).
21462  */
21463  if( nBlock <= MX_SMALL ){
21464  i = mem3.aiSmall[nBlock-2];
21465  if( i>0 ){
21466  memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
21467  return memsys3Checkout(i, nBlock);
21468  }
21469  }else{
21470  int hash = nBlock % N_HASH;
21471  for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
21472  if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
21473  memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
21474  return memsys3Checkout(i, nBlock);
21475  }
21476  }
21477  }
21478 
21479  /* STEP 2:
21480  ** Try to satisfy the allocation by carving a piece off of the end
21481  ** of the master chunk. This step usually works if step 1 fails.
21482  */
21483  if( mem3.szMaster>=nBlock ){
21484  return memsys3FromMaster(nBlock);
21485  }
21486 
21487 
21488  /* STEP 3:
21489  ** Loop through the entire memory pool. Coalesce adjacent free
21490  ** chunks. Recompute the master chunk as the largest free chunk.
21491  ** Then try again to satisfy the allocation by carving a piece off
21492  ** of the end of the master chunk. This step happens very
21493  ** rarely (we hope!)
21494  */
21495  for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
21496  memsys3OutOfMemory(toFree);
21497  if( mem3.iMaster ){
21498  memsys3Link(mem3.iMaster);
21499  mem3.iMaster = 0;
21500  mem3.szMaster = 0;
21501  }
21502  for(i=0; i<N_HASH; i++){
21503  memsys3Merge(&mem3.aiHash[i]);
21504  }
21505  for(i=0; i<MX_SMALL-1; i++){
21506  memsys3Merge(&mem3.aiSmall[i]);
21507  }
21508  if( mem3.szMaster ){
21509  memsys3Unlink(mem3.iMaster);
21510  if( mem3.szMaster>=nBlock ){
21511  return memsys3FromMaster(nBlock);
21512  }
21513  }
21514  }
21515 
21516  /* If none of the above worked, then we fail. */
21517  return 0;
21518 }
21519 
21520 /*
21521 ** Free an outstanding memory allocation.
21522 **
21523 ** This function assumes that the necessary mutexes, if any, are
21524 ** already held by the caller. Hence "Unsafe".
21525 */
21526 static void memsys3FreeUnsafe(void *pOld){
21527  Mem3Block *p = (Mem3Block*)pOld;
21528  int i;
21529  u32 size, x;
21530  assert( sqlite3_mutex_held(mem3.mutex) );
21531  assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
21532  i = p - mem3.aPool;
21533  assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
21534  size = mem3.aPool[i-1].u.hdr.size4x/4;
21535  assert( i+size<=mem3.nPool+1 );
21536  mem3.aPool[i-1].u.hdr.size4x &= ~1;
21537  mem3.aPool[i+size-1].u.hdr.prevSize = size;
21538  mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
21539  memsys3Link(i);
21540 
21541  /* Try to expand the master using the newly freed chunk */
21542  if( mem3.iMaster ){
21543  while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
21544  size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
21545  mem3.iMaster -= size;
21546  mem3.szMaster += size;
21547  memsys3Unlink(mem3.iMaster);
21548  x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
21549  mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
21550  mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
21551  }
21552  x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
21553  while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
21554  memsys3Unlink(mem3.iMaster+mem3.szMaster);
21555  mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
21556  mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
21557  mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
21558  }
21559  }
21560 }
21561 
21562 /*
21563 ** Return the size of an outstanding allocation, in bytes. The
21564 ** size returned omits the 8-byte header overhead. This only
21565 ** works for chunks that are currently checked out.
21566 */
21567 static int memsys3Size(void *p){
21568  Mem3Block *pBlock;
21569  assert( p!=0 );
21570  pBlock = (Mem3Block*)p;
21571  assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
21572  return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
21573 }
21574 
21575 /*
21576 ** Round up a request size to the next valid allocation size.
21577 */
21578 static int memsys3Roundup(int n){
21579  if( n<=12 ){
21580  return 12;
21581  }else{
21582  return ((n+11)&~7) - 4;
21583  }
21584 }
21585 
21586 /*
21587 ** Allocate nBytes of memory.
21588 */
21589 static void *memsys3Malloc(int nBytes){
21590  sqlite3_int64 *p;
21591  assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
21592  memsys3Enter();
21593  p = memsys3MallocUnsafe(nBytes);
21594  memsys3Leave();
21595  return (void*)p;
21596 }
21597 
21598 /*
21599 ** Free memory.
21600 */
21601 static void memsys3Free(void *pPrior){
21602  assert( pPrior );
21603  memsys3Enter();
21604  memsys3FreeUnsafe(pPrior);
21605  memsys3Leave();
21606 }
21607 
21608 /*
21609 ** Change the size of an existing memory allocation
21610 */
21611 static void *memsys3Realloc(void *pPrior, int nBytes){
21612  int nOld;
21613  void *p;
21614  if( pPrior==0 ){
21615  return sqlite3_malloc(nBytes);
21616  }
21617  if( nBytes<=0 ){
21618  sqlite3_free(pPrior);
21619  return 0;
21620  }
21621  nOld = memsys3Size(pPrior);
21622  if( nBytes<=nOld && nBytes>=nOld-128 ){
21623  return pPrior;
21624  }
21625  memsys3Enter();
21626  p = memsys3MallocUnsafe(nBytes);
21627  if( p ){
21628  if( nOld<nBytes ){
21629  memcpy(p, pPrior, nOld);
21630  }else{
21631  memcpy(p, pPrior, nBytes);
21632  }
21633  memsys3FreeUnsafe(pPrior);
21634  }
21635  memsys3Leave();
21636  return p;
21637 }
21638 
21639 /*
21640 ** Initialize this module.
21641 */
21642 static int memsys3Init(void *NotUsed){
21643  UNUSED_PARAMETER(NotUsed);
21644  if( !sqlite3GlobalConfig.pHeap ){
21645  return SQLITE_ERROR;
21646  }
21647 
21648  /* Store a pointer to the memory block in global structure mem3. */
21649  assert( sizeof(Mem3Block)==8 );
21650  mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
21651  mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
21652 
21653  /* Initialize the master block. */
21654  mem3.szMaster = mem3.nPool;
21655  mem3.mnMaster = mem3.szMaster;
21656  mem3.iMaster = 1;
21657  mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
21658  mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
21659  mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
21660 
21661  return SQLITE_OK;
21662 }
21663 
21664 /*
21665 ** Deinitialize this module.
21666 */
21667 static void memsys3Shutdown(void *NotUsed){
21668  UNUSED_PARAMETER(NotUsed);
21669  mem3.mutex = 0;
21670  return;
21671 }
21672 
21673 
21674 
21675 /*
21676 ** Open the file indicated and write a log of all unfreed memory
21677 ** allocations into that log.
21678 */
21679 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
21680 #ifdef SQLITE_DEBUG
21681  FILE *out;
21682  u32 i, j;
21683  u32 size;
21684  if( zFilename==0 || zFilename[0]==0 ){
21685  out = stdout;
21686  }else{
21687  out = fopen(zFilename, "w");
21688  if( out==0 ){
21689  fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
21690  zFilename);
21691  return;
21692  }
21693  }
21694  memsys3Enter();
21695  fprintf(out, "CHUNKS:\n");
21696  for(i=1; i<=mem3.nPool; i+=size/4){
21697  size = mem3.aPool[i-1].u.hdr.size4x;
21698  if( size/4<=1 ){
21699  fprintf(out, "%p size error\n", &mem3.aPool[i]);
21700  assert( 0 );
21701  break;
21702  }
21703  if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
21704  fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
21705  assert( 0 );
21706  break;
21707  }
21708  if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
21709  fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
21710  assert( 0 );
21711  break;
21712  }
21713  if( size&1 ){
21714  fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
21715  }else{
21716  fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
21717  i==mem3.iMaster ? " **master**" : "");
21718  }
21719  }
21720  for(i=0; i<MX_SMALL-1; i++){
21721  if( mem3.aiSmall[i]==0 ) continue;
21722  fprintf(out, "small(%2d):", i);
21723  for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
21724  fprintf(out, " %p(%d)", &mem3.aPool[j],
21725  (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
21726  }
21727  fprintf(out, "\n");
21728  }
21729  for(i=0; i<N_HASH; i++){
21730  if( mem3.aiHash[i]==0 ) continue;
21731  fprintf(out, "hash(%2d):", i);
21732  for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
21733  fprintf(out, " %p(%d)", &mem3.aPool[j],
21734  (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
21735  }
21736  fprintf(out, "\n");
21737  }
21738  fprintf(out, "master=%d\n", mem3.iMaster);
21739  fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
21740  fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
21741  sqlite3_mutex_leave(mem3.mutex);
21742  if( out==stdout ){
21743  fflush(stdout);
21744  }else{
21745  fclose(out);
21746  }
21747 #else
21748  UNUSED_PARAMETER(zFilename);
21749 #endif
21750 }
21751 
21752 /*
21753 ** This routine is the only routine in this file with external
21754 ** linkage.
21755 **
21756 ** Populate the low-level memory allocation function pointers in
21757 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
21758 ** arguments specify the block of memory to manage.
21759 **
21760 ** This routine is only called by sqlite3_config(), and therefore
21761 ** is not required to be threadsafe (it is not).
21762 */
21763 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
21764  static const sqlite3_mem_methods mempoolMethods = {
21765  memsys3Malloc,
21766  memsys3Free,
21767  memsys3Realloc,
21768  memsys3Size,
21769  memsys3Roundup,
21770  memsys3Init,
21771  memsys3Shutdown,
21772  0
21773  };
21774  return &mempoolMethods;
21775 }
21776 
21777 #endif /* SQLITE_ENABLE_MEMSYS3 */
21778 
21779 /************** End of mem3.c ************************************************/
21780 /************** Begin file mem5.c ********************************************/
21781 /*
21782 ** 2007 October 14
21783 **
21784 ** The author disclaims copyright to this source code. In place of
21785 ** a legal notice, here is a blessing:
21786 **
21787 ** May you do good and not evil.
21788 ** May you find forgiveness for yourself and forgive others.
21789 ** May you share freely, never taking more than you give.
21790 **
21791 *************************************************************************
21792 ** This file contains the C functions that implement a memory
21793 ** allocation subsystem for use by SQLite.
21794 **
21795 ** This version of the memory allocation subsystem omits all
21796 ** use of malloc(). The application gives SQLite a block of memory
21797 ** before calling sqlite3_initialize() from which allocations
21798 ** are made and returned by the xMalloc() and xRealloc()
21799 ** implementations. Once sqlite3_initialize() has been called,
21800 ** the amount of memory available to SQLite is fixed and cannot
21801 ** be changed.
21802 **
21803 ** This version of the memory allocation subsystem is included
21804 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
21805 **
21806 ** This memory allocator uses the following algorithm:
21807 **
21808 ** 1. All memory allocation sizes are rounded up to a power of 2.
21809 **
21810 ** 2. If two adjacent free blocks are the halves of a larger block,
21811 ** then the two blocks are coalesced into the single larger block.
21812 **
21813 ** 3. New memory is allocated from the first available free block.
21814 **
21815 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
21816 ** Concerning Dynamic Storage Allocation". Journal of the Association for
21817 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
21818 **
21819 ** Let n be the size of the largest allocation divided by the minimum
21820 ** allocation size (after rounding all sizes up to a power of 2.) Let M
21821 ** be the maximum amount of memory ever outstanding at one time. Let
21822 ** N be the total amount of memory available for allocation. Robson
21823 ** proved that this memory allocator will never breakdown due to
21824 ** fragmentation as long as the following constraint holds:
21825 **
21826 ** N >= M*(1 + log2(n)/2) - n + 1
21827 **
21828 ** The sqlite3_status() logic tracks the maximum values of n and M so
21829 ** that an application can, at any time, verify this constraint.
21830 */
21831 /* #include "sqliteInt.h" */
21832 
21833 /*
21834 ** This version of the memory allocator is used only when
21835 ** SQLITE_ENABLE_MEMSYS5 is defined.
21836 */
21837 #ifdef SQLITE_ENABLE_MEMSYS5
21838 
21839 /*
21840 ** A minimum allocation is an instance of the following structure.
21841 ** Larger allocations are an array of these structures where the
21842 ** size of the array is a power of 2.
21843 **
21844 ** The size of this object must be a power of two. That fact is
21845 ** verified in memsys5Init().
21846 */
21847 typedef struct Mem5Link Mem5Link;
21848 struct Mem5Link {
21849  int next; /* Index of next free chunk */
21850  int prev; /* Index of previous free chunk */
21851 };
21852 
21853 /*
21854 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
21855 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
21856 ** it is not actually possible to reach this limit.
21857 */
21858 #define LOGMAX 30
21859 
21860 /*
21861 ** Masks used for mem5.aCtrl[] elements.
21862 */
21863 #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
21864 #define CTRL_FREE 0x20 /* True if not checked out */
21865 
21866 /*
21867 ** All of the static variables used by this module are collected
21868 ** into a single structure named "mem5". This is to keep the
21869 ** static variables organized and to reduce namespace pollution
21870 ** when this module is combined with other in the amalgamation.
21871 */
21872 static SQLITE_WSD struct Mem5Global {
21873  /*
21874  ** Memory available for allocation
21875  */
21876  int szAtom; /* Smallest possible allocation in bytes */
21877  int nBlock; /* Number of szAtom sized blocks in zPool */
21878  u8 *zPool; /* Memory available to be allocated */
21879 
21880  /*
21881  ** Mutex to control access to the memory allocation subsystem.
21882  */
21883  sqlite3_mutex *mutex;
21884 
21885 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
21886  /*
21887  ** Performance statistics
21888  */
21889  u64 nAlloc; /* Total number of calls to malloc */
21890  u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
21891  u64 totalExcess; /* Total internal fragmentation */
21892  u32 currentOut; /* Current checkout, including internal fragmentation */
21893  u32 currentCount; /* Current number of distinct checkouts */
21894  u32 maxOut; /* Maximum instantaneous currentOut */
21895  u32 maxCount; /* Maximum instantaneous currentCount */
21896  u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
21897 #endif
21898 
21899  /*
21900  ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
21901  ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
21902  ** aiFreelist[2] holds free blocks of size szAtom*4. And so forth.
21903  */
21904  int aiFreelist[LOGMAX+1];
21905 
21906  /*
21907  ** Space for tracking which blocks are checked out and the size
21908  ** of each block. One byte per block.
21909  */
21910  u8 *aCtrl;
21911 
21912 } mem5;
21913 
21914 /*
21915 ** Access the static variable through a macro for SQLITE_OMIT_WSD.
21916 */
21917 #define mem5 GLOBAL(struct Mem5Global, mem5)
21918 
21919 /*
21920 ** Assuming mem5.zPool is divided up into an array of Mem5Link
21921 ** structures, return a pointer to the idx-th such link.
21922 */
21923 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
21924 
21925 /*
21926 ** Unlink the chunk at mem5.aPool[i] from list it is currently
21927 ** on. It should be found on mem5.aiFreelist[iLogsize].
21928 */
21929 static void memsys5Unlink(int i, int iLogsize){
21930  int next, prev;
21931  assert( i>=0 && i<mem5.nBlock );
21932  assert( iLogsize>=0 && iLogsize<=LOGMAX );
21933  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
21934 
21935  next = MEM5LINK(i)->next;
21936  prev = MEM5LINK(i)->prev;
21937  if( prev<0 ){
21938  mem5.aiFreelist[iLogsize] = next;
21939  }else{
21940  MEM5LINK(prev)->next = next;
21941  }
21942  if( next>=0 ){
21943  MEM5LINK(next)->prev = prev;
21944  }
21945 }
21946 
21947 /*
21948 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
21949 ** free list.
21950 */
21951 static void memsys5Link(int i, int iLogsize){
21952  int x;
21953  assert( sqlite3_mutex_held(mem5.mutex) );
21954  assert( i>=0 && i<mem5.nBlock );
21955  assert( iLogsize>=0 && iLogsize<=LOGMAX );
21956  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
21957 
21958  x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
21959  MEM5LINK(i)->prev = -1;
21960  if( x>=0 ){
21961  assert( x<mem5.nBlock );
21962  MEM5LINK(x)->prev = i;
21963  }
21964  mem5.aiFreelist[iLogsize] = i;
21965 }
21966 
21967 /*
21968 ** Obtain or release the mutex needed to access global data structures.
21969 */
21970 static void memsys5Enter(void){
21971  sqlite3_mutex_enter(mem5.mutex);
21972 }
21973 static void memsys5Leave(void){
21974  sqlite3_mutex_leave(mem5.mutex);
21975 }
21976 
21977 /*
21978 ** Return the size of an outstanding allocation, in bytes.
21979 ** This only works for chunks that are currently checked out.
21980 */
21981 static int memsys5Size(void *p){
21982  int iSize, i;
21983  assert( p!=0 );
21984  i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
21985  assert( i>=0 && i<mem5.nBlock );
21986  iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
21987  return iSize;
21988 }
21989 
21990 /*
21991 ** Return a block of memory of at least nBytes in size.
21992 ** Return NULL if unable. Return NULL if nBytes==0.
21993 **
21994 ** The caller guarantees that nByte is positive.
21995 **
21996 ** The caller has obtained a mutex prior to invoking this
21997 ** routine so there is never any chance that two or more
21998 ** threads can be in this routine at the same time.
21999 */
22000 static void *memsys5MallocUnsafe(int nByte){
22001  int i; /* Index of a mem5.aPool[] slot */
22002  int iBin; /* Index into mem5.aiFreelist[] */
22003  int iFullSz; /* Size of allocation rounded up to power of 2 */
22004  int iLogsize; /* Log2 of iFullSz/POW2_MIN */
22005 
22006  /* nByte must be a positive */
22007  assert( nByte>0 );
22008 
22009  /* No more than 1GiB per allocation */
22010  if( nByte > 0x40000000 ) return 0;
22011 
22012 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
22013  /* Keep track of the maximum allocation request. Even unfulfilled
22014  ** requests are counted */
22015  if( (u32)nByte>mem5.maxRequest ){
22016  mem5.maxRequest = nByte;
22017  }
22018 #endif
22019 
22020 
22021  /* Round nByte up to the next valid power of two */
22022  for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
22023 
22024  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
22025  ** block. If not, then split a block of the next larger power of
22026  ** two in order to create a new free block of size iLogsize.
22027  */
22028  for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
22029  if( iBin>LOGMAX ){
22030  testcase( sqlite3GlobalConfig.xLog!=0 );
22031  sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
22032  return 0;
22033  }
22034  i = mem5.aiFreelist[iBin];
22035  memsys5Unlink(i, iBin);
22036  while( iBin>iLogsize ){
22037  int newSize;
22038 
22039  iBin--;
22040  newSize = 1 << iBin;
22041  mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
22042  memsys5Link(i+newSize, iBin);
22043  }
22044  mem5.aCtrl[i] = iLogsize;
22045 
22046 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
22047  /* Update allocator performance statistics. */
22048  mem5.nAlloc++;
22049  mem5.totalAlloc += iFullSz;
22050  mem5.totalExcess += iFullSz - nByte;
22051  mem5.currentCount++;
22052  mem5.currentOut += iFullSz;
22053  if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
22054  if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
22055 #endif
22056 
22057 #ifdef SQLITE_DEBUG
22058  /* Make sure the allocated memory does not assume that it is set to zero
22059  ** or retains a value from a previous allocation */
22060  memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
22061 #endif
22062 
22063  /* Return a pointer to the allocated memory. */
22064  return (void*)&mem5.zPool[i*mem5.szAtom];
22065 }
22066 
22067 /*
22068 ** Free an outstanding memory allocation.
22069 */
22070 static void memsys5FreeUnsafe(void *pOld){
22071  u32 size, iLogsize;
22072  int iBlock;
22073 
22074  /* Set iBlock to the index of the block pointed to by pOld in
22075  ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
22076  */
22077  iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
22078 
22079  /* Check that the pointer pOld points to a valid, non-free block. */
22080  assert( iBlock>=0 && iBlock<mem5.nBlock );
22081  assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
22082  assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
22083 
22084  iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
22085  size = 1<<iLogsize;
22086  assert( iBlock+size-1<(u32)mem5.nBlock );
22087 
22088  mem5.aCtrl[iBlock] |= CTRL_FREE;
22089  mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
22090 
22091 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
22092  assert( mem5.currentCount>0 );
22093  assert( mem5.currentOut>=(size*mem5.szAtom) );
22094  mem5.currentCount--;
22095  mem5.currentOut -= size*mem5.szAtom;
22096  assert( mem5.currentOut>0 || mem5.currentCount==0 );
22097  assert( mem5.currentCount>0 || mem5.currentOut==0 );
22098 #endif
22099 
22100  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
22101  while( ALWAYS(iLogsize<LOGMAX) ){
22102  int iBuddy;
22103  if( (iBlock>>iLogsize) & 1 ){
22104  iBuddy = iBlock - size;
22105  assert( iBuddy>=0 );
22106  }else{
22107  iBuddy = iBlock + size;
22108  if( iBuddy>=mem5.nBlock ) break;
22109  }
22110  if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
22111  memsys5Unlink(iBuddy, iLogsize);
22112  iLogsize++;
22113  if( iBuddy<iBlock ){
22114  mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
22115  mem5.aCtrl[iBlock] = 0;
22116  iBlock = iBuddy;
22117  }else{
22118  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
22119  mem5.aCtrl[iBuddy] = 0;
22120  }
22121  size *= 2;
22122  }
22123 
22124 #ifdef SQLITE_DEBUG
22125  /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
22126  ** not used after being freed */
22127  memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
22128 #endif
22129 
22130  memsys5Link(iBlock, iLogsize);
22131 }
22132 
22133 /*
22134 ** Allocate nBytes of memory.
22135 */
22136 static void *memsys5Malloc(int nBytes){
22137  sqlite3_int64 *p = 0;
22138  if( nBytes>0 ){
22139  memsys5Enter();
22140  p = memsys5MallocUnsafe(nBytes);
22141  memsys5Leave();
22142  }
22143  return (void*)p;
22144 }
22145 
22146 /*
22147 ** Free memory.
22148 **
22149 ** The outer layer memory allocator prevents this routine from
22150 ** being called with pPrior==0.
22151 */
22152 static void memsys5Free(void *pPrior){
22153  assert( pPrior!=0 );
22154  memsys5Enter();
22155  memsys5FreeUnsafe(pPrior);
22156  memsys5Leave();
22157 }
22158 
22159 /*
22160 ** Change the size of an existing memory allocation.
22161 **
22162 ** The outer layer memory allocator prevents this routine from
22163 ** being called with pPrior==0.
22164 **
22165 ** nBytes is always a value obtained from a prior call to
22166 ** memsys5Round(). Hence nBytes is always a non-negative power
22167 ** of two. If nBytes==0 that means that an oversize allocation
22168 ** (an allocation larger than 0x40000000) was requested and this
22169 ** routine should return 0 without freeing pPrior.
22170 */
22171 static void *memsys5Realloc(void *pPrior, int nBytes){
22172  int nOld;
22173  void *p;
22174  assert( pPrior!=0 );
22175  assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
22176  assert( nBytes>=0 );
22177  if( nBytes==0 ){
22178  return 0;
22179  }
22180  nOld = memsys5Size(pPrior);
22181  if( nBytes<=nOld ){
22182  return pPrior;
22183  }
22184  p = memsys5Malloc(nBytes);
22185  if( p ){
22186  memcpy(p, pPrior, nOld);
22187  memsys5Free(pPrior);
22188  }
22189  return p;
22190 }
22191 
22192 /*
22193 ** Round up a request size to the next valid allocation size. If
22194 ** the allocation is too large to be handled by this allocation system,
22195 ** return 0.
22196 **
22197 ** All allocations must be a power of two and must be expressed by a
22198 ** 32-bit signed integer. Hence the largest allocation is 0x40000000
22199 ** or 1073741824 bytes.
22200 */
22201 static int memsys5Roundup(int n){
22202  int iFullSz;
22203  if( n > 0x40000000 ) return 0;
22204  for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
22205  return iFullSz;
22206 }
22207 
22208 /*
22209 ** Return the ceiling of the logarithm base 2 of iValue.
22210 **
22211 ** Examples: memsys5Log(1) -> 0
22212 ** memsys5Log(2) -> 1
22213 ** memsys5Log(4) -> 2
22214 ** memsys5Log(5) -> 3
22215 ** memsys5Log(8) -> 3
22216 ** memsys5Log(9) -> 4
22217 */
22218 static int memsys5Log(int iValue){
22219  int iLog;
22220  for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
22221  return iLog;
22222 }
22223 
22224 /*
22225 ** Initialize the memory allocator.
22226 **
22227 ** This routine is not threadsafe. The caller must be holding a mutex
22228 ** to prevent multiple threads from entering at the same time.
22229 */
22230 static int memsys5Init(void *NotUsed){
22231  int ii; /* Loop counter */
22232  int nByte; /* Number of bytes of memory available to this allocator */
22233  u8 *zByte; /* Memory usable by this allocator */
22234  int nMinLog; /* Log base 2 of minimum allocation size in bytes */
22235  int iOffset; /* An offset into mem5.aCtrl[] */
22236 
22237  UNUSED_PARAMETER(NotUsed);
22238 
22239  /* For the purposes of this routine, disable the mutex */
22240  mem5.mutex = 0;
22241 
22242  /* The size of a Mem5Link object must be a power of two. Verify that
22243  ** this is case.
22244  */
22245  assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
22246 
22247  nByte = sqlite3GlobalConfig.nHeap;
22248  zByte = (u8*)sqlite3GlobalConfig.pHeap;
22249  assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
22250 
22251  /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
22252  nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
22253  mem5.szAtom = (1<<nMinLog);
22254  while( (int)sizeof(Mem5Link)>mem5.szAtom ){
22255  mem5.szAtom = mem5.szAtom << 1;
22256  }
22257 
22258  mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
22259  mem5.zPool = zByte;
22260  mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
22261 
22262  for(ii=0; ii<=LOGMAX; ii++){
22263  mem5.aiFreelist[ii] = -1;
22264  }
22265 
22266  iOffset = 0;
22267  for(ii=LOGMAX; ii>=0; ii--){
22268  int nAlloc = (1<<ii);
22269  if( (iOffset+nAlloc)<=mem5.nBlock ){
22270  mem5.aCtrl[iOffset] = ii | CTRL_FREE;
22271  memsys5Link(iOffset, ii);
22272  iOffset += nAlloc;
22273  }
22274  assert((iOffset+nAlloc)>mem5.nBlock);
22275  }
22276 
22277  /* If a mutex is required for normal operation, allocate one */
22278  if( sqlite3GlobalConfig.bMemstat==0 ){
22279  mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
22280  }
22281 
22282  return SQLITE_OK;
22283 }
22284 
22285 /*
22286 ** Deinitialize this module.
22287 */
22288 static void memsys5Shutdown(void *NotUsed){
22289  UNUSED_PARAMETER(NotUsed);
22290  mem5.mutex = 0;
22291  return;
22292 }
22293 
22294 #ifdef SQLITE_TEST
22295 /*
22296 ** Open the file indicated and write a log of all unfreed memory
22297 ** allocations into that log.
22298 */
22299 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
22300  FILE *out;
22301  int i, j, n;
22302  int nMinLog;
22303 
22304  if( zFilename==0 || zFilename[0]==0 ){
22305  out = stdout;
22306  }else{
22307  out = fopen(zFilename, "w");
22308  if( out==0 ){
22309  fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
22310  zFilename);
22311  return;
22312  }
22313  }
22314  memsys5Enter();
22315  nMinLog = memsys5Log(mem5.szAtom);
22316  for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
22317  for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
22318  fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
22319  }
22320  fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
22321  fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
22322  fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
22323  fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
22324  fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
22325  fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
22326  fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
22327  fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
22328  memsys5Leave();
22329  if( out==stdout ){
22330  fflush(stdout);
22331  }else{
22332  fclose(out);
22333  }
22334 }
22335 #endif
22336 
22337 /*
22338 ** This routine is the only routine in this file with external
22339 ** linkage. It returns a pointer to a static sqlite3_mem_methods
22340 ** struct populated with the memsys5 methods.
22341 */
22342 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
22343  static const sqlite3_mem_methods memsys5Methods = {
22344  memsys5Malloc,
22345  memsys5Free,
22346  memsys5Realloc,
22347  memsys5Size,
22348  memsys5Roundup,
22349  memsys5Init,
22350  memsys5Shutdown,
22351  0
22352  };
22353  return &memsys5Methods;
22354 }
22355 
22356 #endif /* SQLITE_ENABLE_MEMSYS5 */
22357 
22358 /************** End of mem5.c ************************************************/
22359 /************** Begin file mutex.c *******************************************/
22360 /*
22361 ** 2007 August 14
22362 **
22363 ** The author disclaims copyright to this source code. In place of
22364 ** a legal notice, here is a blessing:
22365 **
22366 ** May you do good and not evil.
22367 ** May you find forgiveness for yourself and forgive others.
22368 ** May you share freely, never taking more than you give.
22369 **
22370 *************************************************************************
22371 ** This file contains the C functions that implement mutexes.
22372 **
22373 ** This file contains code that is common across all mutex implementations.
22374 */
22375 /* #include "sqliteInt.h" */
22376 
22377 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
22378 /*
22379 ** For debugging purposes, record when the mutex subsystem is initialized
22380 ** and uninitialized so that we can assert() if there is an attempt to
22381 ** allocate a mutex while the system is uninitialized.
22382 */
22383 static SQLITE_WSD int mutexIsInit = 0;
22384 #endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
22385 
22386 
22387 #ifndef SQLITE_MUTEX_OMIT
22388 /*
22389 ** Initialize the mutex system.
22390 */
22391 SQLITE_PRIVATE int sqlite3MutexInit(void){
22392  int rc = SQLITE_OK;
22393  if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
22394  /* If the xMutexAlloc method has not been set, then the user did not
22395  ** install a mutex implementation via sqlite3_config() prior to
22396  ** sqlite3_initialize() being called. This block copies pointers to
22397  ** the default implementation into the sqlite3GlobalConfig structure.
22398  */
22399  sqlite3_mutex_methods const *pFrom;
22400  sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
22401 
22402  if( sqlite3GlobalConfig.bCoreMutex ){
22403  pFrom = sqlite3DefaultMutex();
22404  }else{
22405  pFrom = sqlite3NoopMutex();
22406  }
22407  pTo->xMutexInit = pFrom->xMutexInit;
22408  pTo->xMutexEnd = pFrom->xMutexEnd;
22409  pTo->xMutexFree = pFrom->xMutexFree;
22410  pTo->xMutexEnter = pFrom->xMutexEnter;
22411  pTo->xMutexTry = pFrom->xMutexTry;
22412  pTo->xMutexLeave = pFrom->xMutexLeave;
22413  pTo->xMutexHeld = pFrom->xMutexHeld;
22414  pTo->xMutexNotheld = pFrom->xMutexNotheld;
22415  sqlite3MemoryBarrier();
22416  pTo->xMutexAlloc = pFrom->xMutexAlloc;
22417  }
22418  assert( sqlite3GlobalConfig.mutex.xMutexInit );
22419  rc = sqlite3GlobalConfig.mutex.xMutexInit();
22420 
22421 #ifdef SQLITE_DEBUG
22422  GLOBAL(int, mutexIsInit) = 1;
22423 #endif
22424 
22425  return rc;
22426 }
22427 
22428 /*
22429 ** Shutdown the mutex system. This call frees resources allocated by
22430 ** sqlite3MutexInit().
22431 */
22432 SQLITE_PRIVATE int sqlite3MutexEnd(void){
22433  int rc = SQLITE_OK;
22434  if( sqlite3GlobalConfig.mutex.xMutexEnd ){
22435  rc = sqlite3GlobalConfig.mutex.xMutexEnd();
22436  }
22437 
22438 #ifdef SQLITE_DEBUG
22439  GLOBAL(int, mutexIsInit) = 0;
22440 #endif
22441 
22442  return rc;
22443 }
22444 
22445 /*
22446 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
22447 */
22448 SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_mutex_alloc(int id){
22449 #ifndef SQLITE_OMIT_AUTOINIT
22450  if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
22451  if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
22452 #endif
22453  assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
22454  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
22455 }
22456 
22457 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
22458  if( !sqlite3GlobalConfig.bCoreMutex ){
22459  return 0;
22460  }
22461  assert( GLOBAL(int, mutexIsInit) );
22462  assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
22463  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
22464 }
22465 
22466 /*
22467 ** Free a dynamic mutex.
22468 */
22469 SQLITE_API void SQLITE_STDCALL sqlite3_mutex_free(sqlite3_mutex *p){
22470  if( p ){
22471  assert( sqlite3GlobalConfig.mutex.xMutexFree );
22472  sqlite3GlobalConfig.mutex.xMutexFree(p);
22473  }
22474 }
22475 
22476 /*
22477 ** Obtain the mutex p. If some other thread already has the mutex, block
22478 ** until it can be obtained.
22479 */
22480 SQLITE_API void SQLITE_STDCALL sqlite3_mutex_enter(sqlite3_mutex *p){
22481  if( p ){
22482  assert( sqlite3GlobalConfig.mutex.xMutexEnter );
22483  sqlite3GlobalConfig.mutex.xMutexEnter(p);
22484  }
22485 }
22486 
22487 /*
22488 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
22489 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
22490 */
22491 SQLITE_API int SQLITE_STDCALL sqlite3_mutex_try(sqlite3_mutex *p){
22492  int rc = SQLITE_OK;
22493  if( p ){
22494  assert( sqlite3GlobalConfig.mutex.xMutexTry );
22495  return sqlite3GlobalConfig.mutex.xMutexTry(p);
22496  }
22497  return rc;
22498 }
22499 
22500 /*
22501 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
22502 ** entered by the same thread. The behavior is undefined if the mutex
22503 ** is not currently entered. If a NULL pointer is passed as an argument
22504 ** this function is a no-op.
22505 */
22506 SQLITE_API void SQLITE_STDCALL sqlite3_mutex_leave(sqlite3_mutex *p){
22507  if( p ){
22508  assert( sqlite3GlobalConfig.mutex.xMutexLeave );
22509  sqlite3GlobalConfig.mutex.xMutexLeave(p);
22510  }
22511 }
22512 
22513 #ifndef NDEBUG
22514 /*
22515 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
22516 ** intended for use inside assert() statements.
22517 */
22518 SQLITE_API int SQLITE_STDCALL sqlite3_mutex_held(sqlite3_mutex *p){
22519  assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
22520  return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
22521 }
22522 SQLITE_API int SQLITE_STDCALL sqlite3_mutex_notheld(sqlite3_mutex *p){
22523  assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
22524  return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
22525 }
22526 #endif
22527 
22528 #endif /* !defined(SQLITE_MUTEX_OMIT) */
22529 
22530 /************** End of mutex.c ***********************************************/
22531 /************** Begin file mutex_noop.c **************************************/
22532 /*
22533 ** 2008 October 07
22534 **
22535 ** The author disclaims copyright to this source code. In place of
22536 ** a legal notice, here is a blessing:
22537 **
22538 ** May you do good and not evil.
22539 ** May you find forgiveness for yourself and forgive others.
22540 ** May you share freely, never taking more than you give.
22541 **
22542 *************************************************************************
22543 ** This file contains the C functions that implement mutexes.
22544 **
22545 ** This implementation in this file does not provide any mutual
22546 ** exclusion and is thus suitable for use only in applications
22547 ** that use SQLite in a single thread. The routines defined
22548 ** here are place-holders. Applications can substitute working
22549 ** mutex routines at start-time using the
22550 **
22551 ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
22552 **
22553 ** interface.
22554 **
22555 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
22556 ** that does error checking on mutexes to make sure they are being
22557 ** called correctly.
22558 */
22559 /* #include "sqliteInt.h" */
22560 
22561 #ifndef SQLITE_MUTEX_OMIT
22562 
22563 #ifndef SQLITE_DEBUG
22564 /*
22565 ** Stub routines for all mutex methods.
22566 **
22567 ** This routines provide no mutual exclusion or error checking.
22568 */
22569 static int noopMutexInit(void){ return SQLITE_OK; }
22570 static int noopMutexEnd(void){ return SQLITE_OK; }
22571 static sqlite3_mutex *noopMutexAlloc(int id){
22572  UNUSED_PARAMETER(id);
22573  return (sqlite3_mutex*)8;
22574 }
22575 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
22576 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
22577 static int noopMutexTry(sqlite3_mutex *p){
22578  UNUSED_PARAMETER(p);
22579  return SQLITE_OK;
22580 }
22581 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
22582 
22583 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
22584  static const sqlite3_mutex_methods sMutex = {
22585  noopMutexInit,
22586  noopMutexEnd,
22587  noopMutexAlloc,
22588  noopMutexFree,
22589  noopMutexEnter,
22590  noopMutexTry,
22591  noopMutexLeave,
22592 
22593  0,
22594  0,
22595  };
22596 
22597  return &sMutex;
22598 }
22599 #endif /* !SQLITE_DEBUG */
22600 
22601 #ifdef SQLITE_DEBUG
22602 /*
22603 ** In this implementation, error checking is provided for testing
22604 ** and debugging purposes. The mutexes still do not provide any
22605 ** mutual exclusion.
22606 */
22607 
22608 /*
22609 ** The mutex object
22610 */
22611 typedef struct sqlite3_debug_mutex {
22612  int id; /* The mutex type */
22613  int cnt; /* Number of entries without a matching leave */
22614 } sqlite3_debug_mutex;
22615 
22616 /*
22617 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
22618 ** intended for use inside assert() statements.
22619 */
22620 static int debugMutexHeld(sqlite3_mutex *pX){
22621  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22622  return p==0 || p->cnt>0;
22623 }
22624 static int debugMutexNotheld(sqlite3_mutex *pX){
22625  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22626  return p==0 || p->cnt==0;
22627 }
22628 
22629 /*
22630 ** Initialize and deinitialize the mutex subsystem.
22631 */
22632 static int debugMutexInit(void){ return SQLITE_OK; }
22633 static int debugMutexEnd(void){ return SQLITE_OK; }
22634 
22635 /*
22636 ** The sqlite3_mutex_alloc() routine allocates a new
22637 ** mutex and returns a pointer to it. If it returns NULL
22638 ** that means that a mutex could not be allocated.
22639 */
22640 static sqlite3_mutex *debugMutexAlloc(int id){
22641  static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
22642  sqlite3_debug_mutex *pNew = 0;
22643  switch( id ){
22644  case SQLITE_MUTEX_FAST:
22645  case SQLITE_MUTEX_RECURSIVE: {
22646  pNew = sqlite3Malloc(sizeof(*pNew));
22647  if( pNew ){
22648  pNew->id = id;
22649  pNew->cnt = 0;
22650  }
22651  break;
22652  }
22653  default: {
22654 #ifdef SQLITE_ENABLE_API_ARMOR
22655  if( id-2<0 || id-2>=ArraySize(aStatic) ){
22656  (void)SQLITE_MISUSE_BKPT;
22657  return 0;
22658  }
22659 #endif
22660  pNew = &aStatic[id-2];
22661  pNew->id = id;
22662  break;
22663  }
22664  }
22665  return (sqlite3_mutex*)pNew;
22666 }
22667 
22668 /*
22669 ** This routine deallocates a previously allocated mutex.
22670 */
22671 static void debugMutexFree(sqlite3_mutex *pX){
22672  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22673  assert( p->cnt==0 );
22674  if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
22675  sqlite3_free(p);
22676  }else{
22677 #ifdef SQLITE_ENABLE_API_ARMOR
22678  (void)SQLITE_MISUSE_BKPT;
22679 #endif
22680  }
22681 }
22682 
22683 /*
22684 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
22685 ** to enter a mutex. If another thread is already within the mutex,
22686 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
22687 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
22688 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
22689 ** be entered multiple times by the same thread. In such cases the,
22690 ** mutex must be exited an equal number of times before another thread
22691 ** can enter. If the same thread tries to enter any other kind of mutex
22692 ** more than once, the behavior is undefined.
22693 */
22694 static void debugMutexEnter(sqlite3_mutex *pX){
22695  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22696  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
22697  p->cnt++;
22698 }
22699 static int debugMutexTry(sqlite3_mutex *pX){
22700  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22701  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
22702  p->cnt++;
22703  return SQLITE_OK;
22704 }
22705 
22706 /*
22707 ** The sqlite3_mutex_leave() routine exits a mutex that was
22708 ** previously entered by the same thread. The behavior
22709 ** is undefined if the mutex is not currently entered or
22710 ** is not currently allocated. SQLite will never do either.
22711 */
22712 static void debugMutexLeave(sqlite3_mutex *pX){
22713  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22714  assert( debugMutexHeld(pX) );
22715  p->cnt--;
22716  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
22717 }
22718 
22719 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
22720  static const sqlite3_mutex_methods sMutex = {
22721  debugMutexInit,
22722  debugMutexEnd,
22723  debugMutexAlloc,
22724  debugMutexFree,
22725  debugMutexEnter,
22726  debugMutexTry,
22727  debugMutexLeave,
22728 
22729  debugMutexHeld,
22730  debugMutexNotheld
22731  };
22732 
22733  return &sMutex;
22734 }
22735 #endif /* SQLITE_DEBUG */
22736 
22737 /*
22738 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
22739 ** is used regardless of the run-time threadsafety setting.
22740 */
22741 #ifdef SQLITE_MUTEX_NOOP
22742 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
22743  return sqlite3NoopMutex();
22744 }
22745 #endif /* defined(SQLITE_MUTEX_NOOP) */
22746 #endif /* !defined(SQLITE_MUTEX_OMIT) */
22747 
22748 /************** End of mutex_noop.c ******************************************/
22749 /************** Begin file mutex_unix.c **************************************/
22750 /*
22751 ** 2007 August 28
22752 **
22753 ** The author disclaims copyright to this source code. In place of
22754 ** a legal notice, here is a blessing:
22755 **
22756 ** May you do good and not evil.
22757 ** May you find forgiveness for yourself and forgive others.
22758 ** May you share freely, never taking more than you give.
22759 **
22760 *************************************************************************
22761 ** This file contains the C functions that implement mutexes for pthreads
22762 */
22763 /* #include "sqliteInt.h" */
22764 
22765 /*
22766 ** The code in this file is only used if we are compiling threadsafe
22767 ** under unix with pthreads.
22768 **
22769 ** Note that this implementation requires a version of pthreads that
22770 ** supports recursive mutexes.
22771 */
22772 #ifdef SQLITE_MUTEX_PTHREADS
22773 
22774 #include <pthread.h>
22775 
22776 /*
22777 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
22778 ** are necessary under two condidtions: (1) Debug builds and (2) using
22779 ** home-grown mutexes. Encapsulate these conditions into a single #define.
22780 */
22781 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
22782 # define SQLITE_MUTEX_NREF 1
22783 #else
22784 # define SQLITE_MUTEX_NREF 0
22785 #endif
22786 
22787 /*
22788 ** Each recursive mutex is an instance of the following structure.
22789 */
22791  pthread_mutex_t mutex; /* Mutex controlling the lock */
22792 #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
22793  int id; /* Mutex type */
22794 #endif
22795 #if SQLITE_MUTEX_NREF
22796  volatile int nRef; /* Number of entrances */
22797  volatile pthread_t owner; /* Thread that is within this mutex */
22798  int trace; /* True to trace changes */
22799 #endif
22800 };
22801 #if SQLITE_MUTEX_NREF
22802 #define SQLITE3_MUTEX_INITIALIZER {PTHREAD_MUTEX_INITIALIZER,0,0,(pthread_t)0,0}
22803 #elif defined(SQLITE_ENABLE_API_ARMOR)
22804 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0 }
22805 #else
22806 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
22807 #endif
22808 
22809 /*
22810 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
22811 ** intended for use only inside assert() statements. On some platforms,
22812 ** there might be race conditions that can cause these routines to
22813 ** deliver incorrect results. In particular, if pthread_equal() is
22814 ** not an atomic operation, then these routines might delivery
22815 ** incorrect results. On most platforms, pthread_equal() is a
22816 ** comparison of two integers and is therefore atomic. But we are
22817 ** told that HPUX is not such a platform. If so, then these routines
22818 ** will not always work correctly on HPUX.
22819 **
22820 ** On those platforms where pthread_equal() is not atomic, SQLite
22821 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
22822 ** make sure no assert() statements are evaluated and hence these
22823 ** routines are never called.
22824 */
22825 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
22826 static int pthreadMutexHeld(sqlite3_mutex *p){
22827  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
22828 }
22829 static int pthreadMutexNotheld(sqlite3_mutex *p){
22830  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
22831 }
22832 #endif
22833 
22834 /*
22835 ** Try to provide a memory barrier operation, needed for initialization
22836 ** and also for the implementation of xShmBarrier in the VFS in cases
22837 ** where SQLite is compiled without mutexes.
22838 */
22839 SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
22840 #if defined(SQLITE_MEMORY_BARRIER)
22841  SQLITE_MEMORY_BARRIER;
22842 #elif defined(__GNUC__) && GCC_VERSION>=4001000
22843  __sync_synchronize();
22844 #endif
22845 }
22846 
22847 /*
22848 ** Initialize and deinitialize the mutex subsystem.
22849 */
22850 static int pthreadMutexInit(void){ return SQLITE_OK; }
22851 static int pthreadMutexEnd(void){ return SQLITE_OK; }
22852 
22853 /*
22854 ** The sqlite3_mutex_alloc() routine allocates a new
22855 ** mutex and returns a pointer to it. If it returns NULL
22856 ** that means that a mutex could not be allocated. SQLite
22857 ** will unwind its stack and return an error. The argument
22858 ** to sqlite3_mutex_alloc() is one of these integer constants:
22859 **
22860 ** <ul>
22861 ** <li> SQLITE_MUTEX_FAST
22862 ** <li> SQLITE_MUTEX_RECURSIVE
22863 ** <li> SQLITE_MUTEX_STATIC_MASTER
22864 ** <li> SQLITE_MUTEX_STATIC_MEM
22865 ** <li> SQLITE_MUTEX_STATIC_OPEN
22866 ** <li> SQLITE_MUTEX_STATIC_PRNG
22867 ** <li> SQLITE_MUTEX_STATIC_LRU
22868 ** <li> SQLITE_MUTEX_STATIC_PMEM
22869 ** <li> SQLITE_MUTEX_STATIC_APP1
22870 ** <li> SQLITE_MUTEX_STATIC_APP2
22871 ** <li> SQLITE_MUTEX_STATIC_APP3
22872 ** <li> SQLITE_MUTEX_STATIC_VFS1
22873 ** <li> SQLITE_MUTEX_STATIC_VFS2
22874 ** <li> SQLITE_MUTEX_STATIC_VFS3
22875 ** </ul>
22876 **
22877 ** The first two constants cause sqlite3_mutex_alloc() to create
22878 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
22879 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
22880 ** The mutex implementation does not need to make a distinction
22881 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
22882 ** not want to. But SQLite will only request a recursive mutex in
22883 ** cases where it really needs one. If a faster non-recursive mutex
22884 ** implementation is available on the host platform, the mutex subsystem
22885 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
22886 **
22887 ** The other allowed parameters to sqlite3_mutex_alloc() each return
22888 ** a pointer to a static preexisting mutex. Six static mutexes are
22889 ** used by the current version of SQLite. Future versions of SQLite
22890 ** may add additional static mutexes. Static mutexes are for internal
22891 ** use by SQLite only. Applications that use SQLite mutexes should
22892 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
22893 ** SQLITE_MUTEX_RECURSIVE.
22894 **
22895 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
22896 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
22897 ** returns a different mutex on every call. But for the static
22898 ** mutex types, the same mutex is returned on every call that has
22899 ** the same type number.
22900 */
22901 static sqlite3_mutex *pthreadMutexAlloc(int iType){
22902  static sqlite3_mutex staticMutexes[] = {
22903  SQLITE3_MUTEX_INITIALIZER,
22904  SQLITE3_MUTEX_INITIALIZER,
22905  SQLITE3_MUTEX_INITIALIZER,
22906  SQLITE3_MUTEX_INITIALIZER,
22907  SQLITE3_MUTEX_INITIALIZER,
22908  SQLITE3_MUTEX_INITIALIZER,
22909  SQLITE3_MUTEX_INITIALIZER,
22910  SQLITE3_MUTEX_INITIALIZER,
22911  SQLITE3_MUTEX_INITIALIZER,
22912  SQLITE3_MUTEX_INITIALIZER,
22913  SQLITE3_MUTEX_INITIALIZER,
22914  SQLITE3_MUTEX_INITIALIZER
22915  };
22916  sqlite3_mutex *p;
22917  switch( iType ){
22918  case SQLITE_MUTEX_RECURSIVE: {
22919  p = sqlite3MallocZero( sizeof(*p) );
22920  if( p ){
22921 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
22922  /* If recursive mutexes are not available, we will have to
22923  ** build our own. See below. */
22924  pthread_mutex_init(&p->mutex, 0);
22925 #else
22926  /* Use a recursive mutex if it is available */
22927  pthread_mutexattr_t recursiveAttr;
22928  pthread_mutexattr_init(&recursiveAttr);
22929  pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
22930  pthread_mutex_init(&p->mutex, &recursiveAttr);
22931  pthread_mutexattr_destroy(&recursiveAttr);
22932 #endif
22933  }
22934  break;
22935  }
22936  case SQLITE_MUTEX_FAST: {
22937  p = sqlite3MallocZero( sizeof(*p) );
22938  if( p ){
22939  pthread_mutex_init(&p->mutex, 0);
22940  }
22941  break;
22942  }
22943  default: {
22944 #ifdef SQLITE_ENABLE_API_ARMOR
22945  if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
22946  (void)SQLITE_MISUSE_BKPT;
22947  return 0;
22948  }
22949 #endif
22950  p = &staticMutexes[iType-2];
22951  break;
22952  }
22953  }
22954 #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
22955  if( p ) p->id = iType;
22956 #endif
22957  return p;
22958 }
22959 
22960 
22961 /*
22962 ** This routine deallocates a previously
22963 ** allocated mutex. SQLite is careful to deallocate every
22964 ** mutex that it allocates.
22965 */
22966 static void pthreadMutexFree(sqlite3_mutex *p){
22967  assert( p->nRef==0 );
22968 #if SQLITE_ENABLE_API_ARMOR
22969  if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
22970 #endif
22971  {
22972  pthread_mutex_destroy(&p->mutex);
22973  sqlite3_free(p);
22974  }
22975 #ifdef SQLITE_ENABLE_API_ARMOR
22976  else{
22977  (void)SQLITE_MISUSE_BKPT;
22978  }
22979 #endif
22980 }
22981 
22982 /*
22983 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
22984 ** to enter a mutex. If another thread is already within the mutex,
22985 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
22986 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
22987 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
22988 ** be entered multiple times by the same thread. In such cases the,
22989 ** mutex must be exited an equal number of times before another thread
22990 ** can enter. If the same thread tries to enter any other kind of mutex
22991 ** more than once, the behavior is undefined.
22992 */
22993 static void pthreadMutexEnter(sqlite3_mutex *p){
22994  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
22995 
22996 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
22997  /* If recursive mutexes are not available, then we have to grow
22998  ** our own. This implementation assumes that pthread_equal()
22999  ** is atomic - that it cannot be deceived into thinking self
23000  ** and p->owner are equal if p->owner changes between two values
23001  ** that are not equal to self while the comparison is taking place.
23002  ** This implementation also assumes a coherent cache - that
23003  ** separate processes cannot read different values from the same
23004  ** address at the same time. If either of these two conditions
23005  ** are not met, then the mutexes will fail and problems will result.
23006  */
23007  {
23008  pthread_t self = pthread_self();
23009  if( p->nRef>0 && pthread_equal(p->owner, self) ){
23010  p->nRef++;
23011  }else{
23012  pthread_mutex_lock(&p->mutex);
23013  assert( p->nRef==0 );
23014  p->owner = self;
23015  p->nRef = 1;
23016  }
23017  }
23018 #else
23019  /* Use the built-in recursive mutexes if they are available.
23020  */
23021  pthread_mutex_lock(&p->mutex);
23022 #if SQLITE_MUTEX_NREF
23023  assert( p->nRef>0 || p->owner==0 );
23024  p->owner = pthread_self();
23025  p->nRef++;
23026 #endif
23027 #endif
23028 
23029 #ifdef SQLITE_DEBUG
23030  if( p->trace ){
23031  printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
23032  }
23033 #endif
23034 }
23035 static int pthreadMutexTry(sqlite3_mutex *p){
23036  int rc;
23037  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
23038 
23039 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
23040  /* If recursive mutexes are not available, then we have to grow
23041  ** our own. This implementation assumes that pthread_equal()
23042  ** is atomic - that it cannot be deceived into thinking self
23043  ** and p->owner are equal if p->owner changes between two values
23044  ** that are not equal to self while the comparison is taking place.
23045  ** This implementation also assumes a coherent cache - that
23046  ** separate processes cannot read different values from the same
23047  ** address at the same time. If either of these two conditions
23048  ** are not met, then the mutexes will fail and problems will result.
23049  */
23050  {
23051  pthread_t self = pthread_self();
23052  if( p->nRef>0 && pthread_equal(p->owner, self) ){
23053  p->nRef++;
23054  rc = SQLITE_OK;
23055  }else if( pthread_mutex_trylock(&p->mutex)==0 ){
23056  assert( p->nRef==0 );
23057  p->owner = self;
23058  p->nRef = 1;
23059  rc = SQLITE_OK;
23060  }else{
23061  rc = SQLITE_BUSY;
23062  }
23063  }
23064 #else
23065  /* Use the built-in recursive mutexes if they are available.
23066  */
23067  if( pthread_mutex_trylock(&p->mutex)==0 ){
23068 #if SQLITE_MUTEX_NREF
23069  p->owner = pthread_self();
23070  p->nRef++;
23071 #endif
23072  rc = SQLITE_OK;
23073  }else{
23074  rc = SQLITE_BUSY;
23075  }
23076 #endif
23077 
23078 #ifdef SQLITE_DEBUG
23079  if( rc==SQLITE_OK && p->trace ){
23080  printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
23081  }
23082 #endif
23083  return rc;
23084 }
23085 
23086 /*
23087 ** The sqlite3_mutex_leave() routine exits a mutex that was
23088 ** previously entered by the same thread. The behavior
23089 ** is undefined if the mutex is not currently entered or
23090 ** is not currently allocated. SQLite will never do either.
23091 */
23092 static void pthreadMutexLeave(sqlite3_mutex *p){
23093  assert( pthreadMutexHeld(p) );
23094 #if SQLITE_MUTEX_NREF
23095  p->nRef--;
23096  if( p->nRef==0 ) p->owner = 0;
23097 #endif
23098  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
23099 
23100 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
23101  if( p->nRef==0 ){
23102  pthread_mutex_unlock(&p->mutex);
23103  }
23104 #else
23105  pthread_mutex_unlock(&p->mutex);
23106 #endif
23107 
23108 #ifdef SQLITE_DEBUG
23109  if( p->trace ){
23110  printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
23111  }
23112 #endif
23113 }
23114 
23115 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
23116  static const sqlite3_mutex_methods sMutex = {
23117  pthreadMutexInit,
23118  pthreadMutexEnd,
23119  pthreadMutexAlloc,
23120  pthreadMutexFree,
23121  pthreadMutexEnter,
23122  pthreadMutexTry,
23123  pthreadMutexLeave,
23124 #ifdef SQLITE_DEBUG
23125  pthreadMutexHeld,
23126  pthreadMutexNotheld
23127 #else
23128  0,
23129  0
23130 #endif
23131  };
23132 
23133  return &sMutex;
23134 }
23135 
23136 #endif /* SQLITE_MUTEX_PTHREADS */
23137 
23138 /************** End of mutex_unix.c ******************************************/
23139 /************** Begin file mutex_w32.c ***************************************/
23140 /*
23141 ** 2007 August 14
23142 **
23143 ** The author disclaims copyright to this source code. In place of
23144 ** a legal notice, here is a blessing:
23145 **
23146 ** May you do good and not evil.
23147 ** May you find forgiveness for yourself and forgive others.
23148 ** May you share freely, never taking more than you give.
23149 **
23150 *************************************************************************
23151 ** This file contains the C functions that implement mutexes for Win32.
23152 */
23153 /* #include "sqliteInt.h" */
23154 
23155 #if SQLITE_OS_WIN
23156 /*
23157 ** Include code that is common to all os_*.c files
23158 */
23159 /************** Include os_common.h in the middle of mutex_w32.c *************/
23160 /************** Begin file os_common.h ***************************************/
23161 /*
23162 ** 2004 May 22
23163 **
23164 ** The author disclaims copyright to this source code. In place of
23165 ** a legal notice, here is a blessing:
23166 **
23167 ** May you do good and not evil.
23168 ** May you find forgiveness for yourself and forgive others.
23169 ** May you share freely, never taking more than you give.
23170 **
23171 ******************************************************************************
23172 **
23173 ** This file contains macros and a little bit of code that is common to
23174 ** all of the platform-specific files (os_*.c) and is #included into those
23175 ** files.
23176 **
23177 ** This file should be #included by the os_*.c files only. It is not a
23178 ** general purpose header file.
23179 */
23180 #ifndef _OS_COMMON_H_
23181 #define _OS_COMMON_H_
23182 
23183 /*
23184 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
23185 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
23186 ** switch. The following code should catch this problem at compile-time.
23187 */
23188 #ifdef MEMORY_DEBUG
23189 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
23190 #endif
23191 
23192 /*
23193 ** Macros for performance tracing. Normally turned off. Only works
23194 ** on i486 hardware.
23195 */
23196 #ifdef SQLITE_PERFORMANCE_TRACE
23197 
23198 /*
23199 ** hwtime.h contains inline assembler code for implementing
23200 ** high-performance timing routines.
23201 */
23202 /************** Include hwtime.h in the middle of os_common.h ****************/
23203 /************** Begin file hwtime.h ******************************************/
23204 /*
23205 ** 2008 May 27
23206 **
23207 ** The author disclaims copyright to this source code. In place of
23208 ** a legal notice, here is a blessing:
23209 **
23210 ** May you do good and not evil.
23211 ** May you find forgiveness for yourself and forgive others.
23212 ** May you share freely, never taking more than you give.
23213 **
23214 ******************************************************************************
23215 **
23216 ** This file contains inline asm code for retrieving "high-performance"
23217 ** counters for x86 class CPUs.
23218 */
23219 #ifndef SQLITE_HWTIME_H
23220 #define SQLITE_HWTIME_H
23221 
23222 /*
23223 ** The following routine only works on pentium-class (or newer) processors.
23224 ** It uses the RDTSC opcode to read the cycle count value out of the
23225 ** processor and returns that value. This can be used for high-res
23226 ** profiling.
23227 */
23228 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
23229  (defined(i386) || defined(__i386__) || defined(_M_IX86))
23230 
23231  #if defined(__GNUC__)
23232 
23233  __inline__ sqlite_uint64 sqlite3Hwtime(void){
23234  unsigned int lo, hi;
23235  __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
23236  return (sqlite_uint64)hi << 32 | lo;
23237  }
23238 
23239  #elif defined(_MSC_VER)
23240 
23241  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
23242  __asm {
23243  rdtsc
23244  ret ; return value at EDX:EAX
23245  }
23246  }
23247 
23248  #endif
23249 
23250 #elif (defined(__GNUC__) && defined(__x86_64__))
23251 
23252  __inline__ sqlite_uint64 sqlite3Hwtime(void){
23253  unsigned long val;
23254  __asm__ __volatile__ ("rdtsc" : "=A" (val));
23255  return val;
23256  }
23257 
23258 #elif (defined(__GNUC__) && defined(__ppc__))
23259 
23260  __inline__ sqlite_uint64 sqlite3Hwtime(void){
23261  unsigned long long retval;
23262  unsigned long junk;
23263  __asm__ __volatile__ ("\n\
23264  1: mftbu %1\n\
23265  mftb %L0\n\
23266  mftbu %0\n\
23267  cmpw %0,%1\n\
23268  bne 1b"
23269  : "=r" (retval), "=r" (junk));
23270  return retval;
23271  }
23272 
23273 #else
23274 
23275  #error Need implementation of sqlite3Hwtime() for your platform.
23276 
23277  /*
23278  ** To compile without implementing sqlite3Hwtime() for your platform,
23279  ** you can remove the above #error and use the following
23280  ** stub function. You will lose timing support for many
23281  ** of the debugging and testing utilities, but it should at
23282  ** least compile and run.
23283  */
23284 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
23285 
23286 #endif
23287 
23288 #endif /* !defined(SQLITE_HWTIME_H) */
23289 
23290 /************** End of hwtime.h **********************************************/
23291 /************** Continuing where we left off in os_common.h ******************/
23292 
23293 static sqlite_uint64 g_start;
23294 static sqlite_uint64 g_elapsed;
23295 #define TIMER_START g_start=sqlite3Hwtime()
23296 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
23297 #define TIMER_ELAPSED g_elapsed
23298 #else
23299 #define TIMER_START
23300 #define TIMER_END
23301 #define TIMER_ELAPSED ((sqlite_uint64)0)
23302 #endif
23303 
23304 /*
23305 ** If we compile with the SQLITE_TEST macro set, then the following block
23306 ** of code will give us the ability to simulate a disk I/O error. This
23307 ** is used for testing the I/O recovery logic.
23308 */
23309 #if defined(SQLITE_TEST)
23310 SQLITE_API extern int sqlite3_io_error_hit;
23311 SQLITE_API extern int sqlite3_io_error_hardhit;
23312 SQLITE_API extern int sqlite3_io_error_pending;
23313 SQLITE_API extern int sqlite3_io_error_persist;
23314 SQLITE_API extern int sqlite3_io_error_benign;
23315 SQLITE_API extern int sqlite3_diskfull_pending;
23316 SQLITE_API extern int sqlite3_diskfull;
23317 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
23318 #define SimulateIOError(CODE) \
23319  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
23320  || sqlite3_io_error_pending-- == 1 ) \
23321  { local_ioerr(); CODE; }
23322 static void local_ioerr(){
23323  IOTRACE(("IOERR\n"));
23324  sqlite3_io_error_hit++;
23325  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
23326 }
23327 #define SimulateDiskfullError(CODE) \
23328  if( sqlite3_diskfull_pending ){ \
23329  if( sqlite3_diskfull_pending == 1 ){ \
23330  local_ioerr(); \
23331  sqlite3_diskfull = 1; \
23332  sqlite3_io_error_hit = 1; \
23333  CODE; \
23334  }else{ \
23335  sqlite3_diskfull_pending--; \
23336  } \
23337  }
23338 #else
23339 #define SimulateIOErrorBenign(X)
23340 #define SimulateIOError(A)
23341 #define SimulateDiskfullError(A)
23342 #endif /* defined(SQLITE_TEST) */
23343 
23344 /*
23345 ** When testing, keep a count of the number of open files.
23346 */
23347 #if defined(SQLITE_TEST)
23348 SQLITE_API extern int sqlite3_open_file_count;
23349 #define OpenCounter(X) sqlite3_open_file_count+=(X)
23350 #else
23351 #define OpenCounter(X)
23352 #endif /* defined(SQLITE_TEST) */
23353 
23354 #endif /* !defined(_OS_COMMON_H_) */
23355 
23356 /************** End of os_common.h *******************************************/
23357 /************** Continuing where we left off in mutex_w32.c ******************/
23358 
23359 /*
23360 ** Include the header file for the Windows VFS.
23361 */
23362 /************** Include os_win.h in the middle of mutex_w32.c ****************/
23363 /************** Begin file os_win.h ******************************************/
23364 /*
23365 ** 2013 November 25
23366 **
23367 ** The author disclaims copyright to this source code. In place of
23368 ** a legal notice, here is a blessing:
23369 **
23370 ** May you do good and not evil.
23371 ** May you find forgiveness for yourself and forgive others.
23372 ** May you share freely, never taking more than you give.
23373 **
23374 ******************************************************************************
23375 **
23376 ** This file contains code that is specific to Windows.
23377 */
23378 #ifndef SQLITE_OS_WIN_H
23379 #define SQLITE_OS_WIN_H
23380 
23381 /*
23382 ** Include the primary Windows SDK header file.
23383 */
23384 #include "windows.h"
23385 
23386 #ifdef __CYGWIN__
23387 # include <sys/cygwin.h>
23388 # include <errno.h> /* amalgamator: dontcache */
23389 #endif
23390 
23391 /*
23392 ** Determine if we are dealing with Windows NT.
23393 **
23394 ** We ought to be able to determine if we are compiling for Windows 9x or
23395 ** Windows NT using the _WIN32_WINNT macro as follows:
23396 **
23397 ** #if defined(_WIN32_WINNT)
23398 ** # define SQLITE_OS_WINNT 1
23399 ** #else
23400 ** # define SQLITE_OS_WINNT 0
23401 ** #endif
23402 **
23403 ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
23404 ** it ought to, so the above test does not work. We'll just assume that
23405 ** everything is Windows NT unless the programmer explicitly says otherwise
23406 ** by setting SQLITE_OS_WINNT to 0.
23407 */
23408 #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
23409 # define SQLITE_OS_WINNT 1
23410 #endif
23411 
23412 /*
23413 ** Determine if we are dealing with Windows CE - which has a much reduced
23414 ** API.
23415 */
23416 #if defined(_WIN32_WCE)
23417 # define SQLITE_OS_WINCE 1
23418 #else
23419 # define SQLITE_OS_WINCE 0
23420 #endif
23421 
23422 /*
23423 ** Determine if we are dealing with WinRT, which provides only a subset of
23424 ** the full Win32 API.
23425 */
23426 #if !defined(SQLITE_OS_WINRT)
23427 # define SQLITE_OS_WINRT 0
23428 #endif
23429 
23430 /*
23431 ** For WinCE, some API function parameters do not appear to be declared as
23432 ** volatile.
23433 */
23434 #if SQLITE_OS_WINCE
23435 # define SQLITE_WIN32_VOLATILE
23436 #else
23437 # define SQLITE_WIN32_VOLATILE volatile
23438 #endif
23439 
23440 /*
23441 ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
23442 ** functions are not available (e.g. those not using MSVC, Cygwin, etc).
23443 */
23444 #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
23445  SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
23446 # define SQLITE_OS_WIN_THREADS 1
23447 #else
23448 # define SQLITE_OS_WIN_THREADS 0
23449 #endif
23450 
23451 #endif /* SQLITE_OS_WIN_H */
23452 
23453 /************** End of os_win.h **********************************************/
23454 /************** Continuing where we left off in mutex_w32.c ******************/
23455 #endif
23456 
23457 /*
23458 ** The code in this file is only used if we are compiling multithreaded
23459 ** on a Win32 system.
23460 */
23461 #ifdef SQLITE_MUTEX_W32
23462 
23463 /*
23464 ** Each recursive mutex is an instance of the following structure.
23465 */
23466 struct sqlite3_mutex {
23467  CRITICAL_SECTION mutex; /* Mutex controlling the lock */
23468  int id; /* Mutex type */
23469 #ifdef SQLITE_DEBUG
23470  volatile int nRef; /* Number of enterances */
23471  volatile DWORD owner; /* Thread holding this mutex */
23472  volatile int trace; /* True to trace changes */
23473 #endif
23474 };
23475 
23476 /*
23477 ** These are the initializer values used when declaring a "static" mutex
23478 ** on Win32. It should be noted that all mutexes require initialization
23479 ** on the Win32 platform.
23480 */
23481 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
23482 
23483 #ifdef SQLITE_DEBUG
23484 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
23485  0L, (DWORD)0, 0 }
23486 #else
23487 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
23488 #endif
23489 
23490 #ifdef SQLITE_DEBUG
23491 /*
23492 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
23493 ** intended for use only inside assert() statements.
23494 */
23495 static int winMutexHeld(sqlite3_mutex *p){
23496  return p->nRef!=0 && p->owner==GetCurrentThreadId();
23497 }
23498 
23499 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
23500  return p->nRef==0 || p->owner!=tid;
23501 }
23502 
23503 static int winMutexNotheld(sqlite3_mutex *p){
23504  DWORD tid = GetCurrentThreadId();
23505  return winMutexNotheld2(p, tid);
23506 }
23507 #endif
23508 
23509 /*
23510 ** Try to provide a memory barrier operation, needed for initialization
23511 ** and also for the xShmBarrier method of the VFS in cases when SQLite is
23512 ** compiled without mutexes (SQLITE_THREADSAFE=0).
23513 */
23514 SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
23515 #if defined(SQLITE_MEMORY_BARRIER)
23516  SQLITE_MEMORY_BARRIER;
23517 #elif defined(__GNUC__)
23518  __sync_synchronize();
23519 #elif !defined(SQLITE_DISABLE_INTRINSIC) && \
23520  defined(_MSC_VER) && _MSC_VER>=1300
23521  _ReadWriteBarrier();
23522 #elif defined(MemoryBarrier)
23523  MemoryBarrier();
23524 #endif
23525 }
23526 
23527 /*
23528 ** Initialize and deinitialize the mutex subsystem.
23529 */
23530 static sqlite3_mutex winMutex_staticMutexes[] = {
23531  SQLITE3_MUTEX_INITIALIZER,
23532  SQLITE3_MUTEX_INITIALIZER,
23533  SQLITE3_MUTEX_INITIALIZER,
23534  SQLITE3_MUTEX_INITIALIZER,
23535  SQLITE3_MUTEX_INITIALIZER,
23536  SQLITE3_MUTEX_INITIALIZER,
23537  SQLITE3_MUTEX_INITIALIZER,
23538  SQLITE3_MUTEX_INITIALIZER,
23539  SQLITE3_MUTEX_INITIALIZER,
23540  SQLITE3_MUTEX_INITIALIZER,
23541  SQLITE3_MUTEX_INITIALIZER,
23542  SQLITE3_MUTEX_INITIALIZER
23543 };
23544 
23545 static int winMutex_isInit = 0;
23546 static int winMutex_isNt = -1; /* <0 means "need to query" */
23547 
23548 /* As the winMutexInit() and winMutexEnd() functions are called as part
23549 ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
23550 ** "interlocked" magic used here is probably not strictly necessary.
23551 */
23552 static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
23553 
23554 SQLITE_API int SQLITE_STDCALL sqlite3_win32_is_nt(void); /* os_win.c */
23555 SQLITE_API void SQLITE_STDCALL sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
23556 
23557 static int winMutexInit(void){
23558  /* The first to increment to 1 does actual initialization */
23559  if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
23560  int i;
23561  for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
23562 #if SQLITE_OS_WINRT
23563  InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
23564 #else
23565  InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
23566 #endif
23567  }
23568  winMutex_isInit = 1;
23569  }else{
23570  /* Another thread is (in the process of) initializing the static
23571  ** mutexes */
23572  while( !winMutex_isInit ){
23573  sqlite3_win32_sleep(1);
23574  }
23575  }
23576  return SQLITE_OK;
23577 }
23578 
23579 static int winMutexEnd(void){
23580  /* The first to decrement to 0 does actual shutdown
23581  ** (which should be the last to shutdown.) */
23582  if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
23583  if( winMutex_isInit==1 ){
23584  int i;
23585  for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
23586  DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
23587  }
23588  winMutex_isInit = 0;
23589  }
23590  }
23591  return SQLITE_OK;
23592 }
23593 
23594 /*
23595 ** The sqlite3_mutex_alloc() routine allocates a new
23596 ** mutex and returns a pointer to it. If it returns NULL
23597 ** that means that a mutex could not be allocated. SQLite
23598 ** will unwind its stack and return an error. The argument
23599 ** to sqlite3_mutex_alloc() is one of these integer constants:
23600 **
23601 ** <ul>
23602 ** <li> SQLITE_MUTEX_FAST
23603 ** <li> SQLITE_MUTEX_RECURSIVE
23604 ** <li> SQLITE_MUTEX_STATIC_MASTER
23605 ** <li> SQLITE_MUTEX_STATIC_MEM
23606 ** <li> SQLITE_MUTEX_STATIC_OPEN
23607 ** <li> SQLITE_MUTEX_STATIC_PRNG
23608 ** <li> SQLITE_MUTEX_STATIC_LRU
23609 ** <li> SQLITE_MUTEX_STATIC_PMEM
23610 ** <li> SQLITE_MUTEX_STATIC_APP1
23611 ** <li> SQLITE_MUTEX_STATIC_APP2
23612 ** <li> SQLITE_MUTEX_STATIC_APP3
23613 ** <li> SQLITE_MUTEX_STATIC_VFS1
23614 ** <li> SQLITE_MUTEX_STATIC_VFS2
23615 ** <li> SQLITE_MUTEX_STATIC_VFS3
23616 ** </ul>
23617 **
23618 ** The first two constants cause sqlite3_mutex_alloc() to create
23619 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
23620 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
23621 ** The mutex implementation does not need to make a distinction
23622 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
23623 ** not want to. But SQLite will only request a recursive mutex in
23624 ** cases where it really needs one. If a faster non-recursive mutex
23625 ** implementation is available on the host platform, the mutex subsystem
23626 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
23627 **
23628 ** The other allowed parameters to sqlite3_mutex_alloc() each return
23629 ** a pointer to a static preexisting mutex. Six static mutexes are
23630 ** used by the current version of SQLite. Future versions of SQLite
23631 ** may add additional static mutexes. Static mutexes are for internal
23632 ** use by SQLite only. Applications that use SQLite mutexes should
23633 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
23634 ** SQLITE_MUTEX_RECURSIVE.
23635 **
23636 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
23637 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
23638 ** returns a different mutex on every call. But for the static
23639 ** mutex types, the same mutex is returned on every call that has
23640 ** the same type number.
23641 */
23642 static sqlite3_mutex *winMutexAlloc(int iType){
23643  sqlite3_mutex *p;
23644 
23645  switch( iType ){
23646  case SQLITE_MUTEX_FAST:
23647  case SQLITE_MUTEX_RECURSIVE: {
23648  p = sqlite3MallocZero( sizeof(*p) );
23649  if( p ){
23650  p->id = iType;
23651 #ifdef SQLITE_DEBUG
23652 #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
23653  p->trace = 1;
23654 #endif
23655 #endif
23656 #if SQLITE_OS_WINRT
23657  InitializeCriticalSectionEx(&p->mutex, 0, 0);
23658 #else
23659  InitializeCriticalSection(&p->mutex);
23660 #endif
23661  }
23662  break;
23663  }
23664  default: {
23665 #ifdef SQLITE_ENABLE_API_ARMOR
23666  if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
23667  (void)SQLITE_MISUSE_BKPT;
23668  return 0;
23669  }
23670 #endif
23671  p = &winMutex_staticMutexes[iType-2];
23672  p->id = iType;
23673 #ifdef SQLITE_DEBUG
23674 #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
23675  p->trace = 1;
23676 #endif
23677 #endif
23678  break;
23679  }
23680  }
23681  return p;
23682 }
23683 
23684 
23685 /*
23686 ** This routine deallocates a previously
23687 ** allocated mutex. SQLite is careful to deallocate every
23688 ** mutex that it allocates.
23689 */
23690 static void winMutexFree(sqlite3_mutex *p){
23691  assert( p );
23692  assert( p->nRef==0 && p->owner==0 );
23693  if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
23694  DeleteCriticalSection(&p->mutex);
23695  sqlite3_free(p);
23696  }else{
23697 #ifdef SQLITE_ENABLE_API_ARMOR
23698  (void)SQLITE_MISUSE_BKPT;
23699 #endif
23700  }
23701 }
23702 
23703 /*
23704 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
23705 ** to enter a mutex. If another thread is already within the mutex,
23706 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
23707 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
23708 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
23709 ** be entered multiple times by the same thread. In such cases the,
23710 ** mutex must be exited an equal number of times before another thread
23711 ** can enter. If the same thread tries to enter any other kind of mutex
23712 ** more than once, the behavior is undefined.
23713 */
23714 static void winMutexEnter(sqlite3_mutex *p){
23715 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
23716  DWORD tid = GetCurrentThreadId();
23717 #endif
23718 #ifdef SQLITE_DEBUG
23719  assert( p );
23720  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
23721 #else
23722  assert( p );
23723 #endif
23724  assert( winMutex_isInit==1 );
23725  EnterCriticalSection(&p->mutex);
23726 #ifdef SQLITE_DEBUG
23727  assert( p->nRef>0 || p->owner==0 );
23728  p->owner = tid;
23729  p->nRef++;
23730  if( p->trace ){
23731  OSTRACE(("ENTER-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
23732  tid, p, p->trace, p->nRef));
23733  }
23734 #endif
23735 }
23736 
23737 static int winMutexTry(sqlite3_mutex *p){
23738 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
23739  DWORD tid = GetCurrentThreadId();
23740 #endif
23741  int rc = SQLITE_BUSY;
23742  assert( p );
23743  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
23744  /*
23745  ** The sqlite3_mutex_try() routine is very rarely used, and when it
23746  ** is used it is merely an optimization. So it is OK for it to always
23747  ** fail.
23748  **
23749  ** The TryEnterCriticalSection() interface is only available on WinNT.
23750  ** And some windows compilers complain if you try to use it without
23751  ** first doing some #defines that prevent SQLite from building on Win98.
23752  ** For that reason, we will omit this optimization for now. See
23753  ** ticket #2685.
23754  */
23755 #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
23756  assert( winMutex_isInit==1 );
23757  assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
23758  if( winMutex_isNt<0 ){
23759  winMutex_isNt = sqlite3_win32_is_nt();
23760  }
23761  assert( winMutex_isNt==0 || winMutex_isNt==1 );
23762  if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
23763 #ifdef SQLITE_DEBUG
23764  p->owner = tid;
23765  p->nRef++;
23766 #endif
23767  rc = SQLITE_OK;
23768  }
23769 #else
23770  UNUSED_PARAMETER(p);
23771 #endif
23772 #ifdef SQLITE_DEBUG
23773  if( p->trace ){
23774  OSTRACE(("TRY-MUTEX tid=%lu, mutex=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
23775  tid, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
23776  }
23777 #endif
23778  return rc;
23779 }
23780 
23781 /*
23782 ** The sqlite3_mutex_leave() routine exits a mutex that was
23783 ** previously entered by the same thread. The behavior
23784 ** is undefined if the mutex is not currently entered or
23785 ** is not currently allocated. SQLite will never do either.
23786 */
23787 static void winMutexLeave(sqlite3_mutex *p){
23788 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
23789  DWORD tid = GetCurrentThreadId();
23790 #endif
23791  assert( p );
23792 #ifdef SQLITE_DEBUG
23793  assert( p->nRef>0 );
23794  assert( p->owner==tid );
23795  p->nRef--;
23796  if( p->nRef==0 ) p->owner = 0;
23797  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
23798 #endif
23799  assert( winMutex_isInit==1 );
23800  LeaveCriticalSection(&p->mutex);
23801 #ifdef SQLITE_DEBUG
23802  if( p->trace ){
23803  OSTRACE(("LEAVE-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
23804  tid, p, p->trace, p->nRef));
23805  }
23806 #endif
23807 }
23808 
23809 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
23810  static const sqlite3_mutex_methods sMutex = {
23811  winMutexInit,
23812  winMutexEnd,
23813  winMutexAlloc,
23814  winMutexFree,
23815  winMutexEnter,
23816  winMutexTry,
23817  winMutexLeave,
23818 #ifdef SQLITE_DEBUG
23819  winMutexHeld,
23820  winMutexNotheld
23821 #else
23822  0,
23823  0
23824 #endif
23825  };
23826  return &sMutex;
23827 }
23828 
23829 #endif /* SQLITE_MUTEX_W32 */
23830 
23831 /************** End of mutex_w32.c *******************************************/
23832 /************** Begin file malloc.c ******************************************/
23833 /*
23834 ** 2001 September 15
23835 **
23836 ** The author disclaims copyright to this source code. In place of
23837 ** a legal notice, here is a blessing:
23838 **
23839 ** May you do good and not evil.
23840 ** May you find forgiveness for yourself and forgive others.
23841 ** May you share freely, never taking more than you give.
23842 **
23843 *************************************************************************
23844 **
23845 ** Memory allocation functions used throughout sqlite.
23846 */
23847 /* #include "sqliteInt.h" */
23848 /* #include <stdarg.h> */
23849 
23850 /*
23851 ** Attempt to release up to n bytes of non-essential memory currently
23852 ** held by SQLite. An example of non-essential memory is memory used to
23853 ** cache database pages that are not currently in use.
23854 */
23855 SQLITE_API int SQLITE_STDCALL sqlite3_release_memory(int n){
23856 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
23857  return sqlite3PcacheReleaseMemory(n);
23858 #else
23859  /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
23860  ** is a no-op returning zero if SQLite is not compiled with
23861  ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
23862  UNUSED_PARAMETER(n);
23863  return 0;
23864 #endif
23865 }
23866 
23867 /*
23868 ** An instance of the following object records the location of
23869 ** each unused scratch buffer.
23870 */
23871 typedef struct ScratchFreeslot {
23872  struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
23873 } ScratchFreeslot;
23874 
23875 /*
23876 ** State information local to the memory allocation subsystem.
23877 */
23878 static SQLITE_WSD struct Mem0Global {
23879  sqlite3_mutex *mutex; /* Mutex to serialize access */
23880  sqlite3_int64 alarmThreshold; /* The soft heap limit */
23881 
23882  /*
23883  ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
23884  ** (so that a range test can be used to determine if an allocation
23885  ** being freed came from pScratch) and a pointer to the list of
23886  ** unused scratch allocations.
23887  */
23888  void *pScratchEnd;
23889  ScratchFreeslot *pScratchFree;
23890  u32 nScratchFree;
23891 
23892  /*
23893  ** True if heap is nearly "full" where "full" is defined by the
23894  ** sqlite3_soft_heap_limit() setting.
23895  */
23896  int nearlyFull;
23897 } mem0 = { 0, 0, 0, 0, 0, 0 };
23898 
23899 #define mem0 GLOBAL(struct Mem0Global, mem0)
23900 
23901 /*
23902 ** Return the memory allocator mutex. sqlite3_status() needs it.
23903 */
23904 SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
23905  return mem0.mutex;
23906 }
23907 
23908 #ifndef SQLITE_OMIT_DEPRECATED
23909 /*
23910 ** Deprecated external interface. It used to set an alarm callback
23911 ** that was invoked when memory usage grew too large. Now it is a
23912 ** no-op.
23913 */
23914 SQLITE_API int SQLITE_STDCALL sqlite3_memory_alarm(
23915  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
23916  void *pArg,
23917  sqlite3_int64 iThreshold
23918 ){
23919  (void)xCallback;
23920  (void)pArg;
23921  (void)iThreshold;
23922  return SQLITE_OK;
23923 }
23924 #endif
23925 
23926 /*
23927 ** Set the soft heap-size limit for the library. Passing a zero or
23928 ** negative value indicates no limit.
23929 */
23930 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_soft_heap_limit64(sqlite3_int64 n){
23931  sqlite3_int64 priorLimit;
23932  sqlite3_int64 excess;
23933  sqlite3_int64 nUsed;
23934 #ifndef SQLITE_OMIT_AUTOINIT
23935  int rc = sqlite3_initialize();
23936  if( rc ) return -1;
23937 #endif
23938  sqlite3_mutex_enter(mem0.mutex);
23939  priorLimit = mem0.alarmThreshold;
23940  if( n<0 ){
23941  sqlite3_mutex_leave(mem0.mutex);
23942  return priorLimit;
23943  }
23944  mem0.alarmThreshold = n;
23945  nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
23946  mem0.nearlyFull = (n>0 && n<=nUsed);
23947  sqlite3_mutex_leave(mem0.mutex);
23948  excess = sqlite3_memory_used() - n;
23949  if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
23950  return priorLimit;
23951 }
23952 SQLITE_API void SQLITE_STDCALL sqlite3_soft_heap_limit(int n){
23953  if( n<0 ) n = 0;
23954  sqlite3_soft_heap_limit64(n);
23955 }
23956 
23957 /*
23958 ** Initialize the memory allocation subsystem.
23959 */
23960 SQLITE_PRIVATE int sqlite3MallocInit(void){
23961  int rc;
23962  if( sqlite3GlobalConfig.m.xMalloc==0 ){
23963  sqlite3MemSetDefault();
23964  }
23965  memset(&mem0, 0, sizeof(mem0));
23966  mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
23967  if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
23968  && sqlite3GlobalConfig.nScratch>0 ){
23969  int i, n, sz;
23970  ScratchFreeslot *pSlot;
23971  sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
23972  sqlite3GlobalConfig.szScratch = sz;
23973  pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
23974  n = sqlite3GlobalConfig.nScratch;
23975  mem0.pScratchFree = pSlot;
23976  mem0.nScratchFree = n;
23977  for(i=0; i<n-1; i++){
23978  pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
23979  pSlot = pSlot->pNext;
23980  }
23981  pSlot->pNext = 0;
23982  mem0.pScratchEnd = (void*)&pSlot[1];
23983  }else{
23984  mem0.pScratchEnd = 0;
23985  sqlite3GlobalConfig.pScratch = 0;
23986  sqlite3GlobalConfig.szScratch = 0;
23987  sqlite3GlobalConfig.nScratch = 0;
23988  }
23989  if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
23990  || sqlite3GlobalConfig.nPage<=0 ){
23991  sqlite3GlobalConfig.pPage = 0;
23992  sqlite3GlobalConfig.szPage = 0;
23993  }
23994  rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
23995  if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
23996  return rc;
23997 }
23998 
23999 /*
24000 ** Return true if the heap is currently under memory pressure - in other
24001 ** words if the amount of heap used is close to the limit set by
24002 ** sqlite3_soft_heap_limit().
24003 */
24004 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
24005  return mem0.nearlyFull;
24006 }
24007 
24008 /*
24009 ** Deinitialize the memory allocation subsystem.
24010 */
24011 SQLITE_PRIVATE void sqlite3MallocEnd(void){
24012  if( sqlite3GlobalConfig.m.xShutdown ){
24013  sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
24014  }
24015  memset(&mem0, 0, sizeof(mem0));
24016 }
24017 
24018 /*
24019 ** Return the amount of memory currently checked out.
24020 */
24021 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_used(void){
24022  sqlite3_int64 res, mx;
24023  sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
24024  return res;
24025 }
24026 
24027 /*
24028 ** Return the maximum amount of memory that has ever been
24029 ** checked out since either the beginning of this process
24030 ** or since the most recent reset.
24031 */
24032 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_highwater(int resetFlag){
24033  sqlite3_int64 res, mx;
24034  sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
24035  return mx;
24036 }
24037 
24038 /*
24039 ** Trigger the alarm
24040 */
24041 static void sqlite3MallocAlarm(int nByte){
24042  if( mem0.alarmThreshold<=0 ) return;
24043  sqlite3_mutex_leave(mem0.mutex);
24044  sqlite3_release_memory(nByte);
24045  sqlite3_mutex_enter(mem0.mutex);
24046 }
24047 
24048 /*
24049 ** Do a memory allocation with statistics and alarms. Assume the
24050 ** lock is already held.
24051 */
24052 static int mallocWithAlarm(int n, void **pp){
24053  int nFull;
24054  void *p;
24055  assert( sqlite3_mutex_held(mem0.mutex) );
24056  nFull = sqlite3GlobalConfig.m.xRoundup(n);
24057  sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
24058  if( mem0.alarmThreshold>0 ){
24059  sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
24060  if( nUsed >= mem0.alarmThreshold - nFull ){
24061  mem0.nearlyFull = 1;
24062  sqlite3MallocAlarm(nFull);
24063  }else{
24064  mem0.nearlyFull = 0;
24065  }
24066  }
24067  p = sqlite3GlobalConfig.m.xMalloc(nFull);
24068 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
24069  if( p==0 && mem0.alarmThreshold>0 ){
24070  sqlite3MallocAlarm(nFull);
24071  p = sqlite3GlobalConfig.m.xMalloc(nFull);
24072  }
24073 #endif
24074  if( p ){
24075  nFull = sqlite3MallocSize(p);
24076  sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
24077  sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
24078  }
24079  *pp = p;
24080  return nFull;
24081 }
24082 
24083 /*
24084 ** Allocate memory. This routine is like sqlite3_malloc() except that it
24085 ** assumes the memory subsystem has already been initialized.
24086 */
24087 SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
24088  void *p;
24089  if( n==0 || n>=0x7fffff00 ){
24090  /* A memory allocation of a number of bytes which is near the maximum
24091  ** signed integer value might cause an integer overflow inside of the
24092  ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
24093  ** 255 bytes of overhead. SQLite itself will never use anything near
24094  ** this amount. The only way to reach the limit is with sqlite3_malloc() */
24095  p = 0;
24096  }else if( sqlite3GlobalConfig.bMemstat ){
24097  sqlite3_mutex_enter(mem0.mutex);
24098  mallocWithAlarm((int)n, &p);
24099  sqlite3_mutex_leave(mem0.mutex);
24100  }else{
24101  p = sqlite3GlobalConfig.m.xMalloc((int)n);
24102  }
24103  assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
24104  return p;
24105 }
24106 
24107 /*
24108 ** This version of the memory allocation is for use by the application.
24109 ** First make sure the memory subsystem is initialized, then do the
24110 ** allocation.
24111 */
24112 SQLITE_API void *SQLITE_STDCALL sqlite3_malloc(int n){
24113 #ifndef SQLITE_OMIT_AUTOINIT
24114  if( sqlite3_initialize() ) return 0;
24115 #endif
24116  return n<=0 ? 0 : sqlite3Malloc(n);
24117 }
24118 SQLITE_API void *SQLITE_STDCALL sqlite3_malloc64(sqlite3_uint64 n){
24119 #ifndef SQLITE_OMIT_AUTOINIT
24120  if( sqlite3_initialize() ) return 0;
24121 #endif
24122  return sqlite3Malloc(n);
24123 }
24124 
24125 /*
24126 ** Each thread may only have a single outstanding allocation from
24127 ** xScratchMalloc(). We verify this constraint in the single-threaded
24128 ** case by setting scratchAllocOut to 1 when an allocation
24129 ** is outstanding clearing it when the allocation is freed.
24130 */
24131 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
24132 static int scratchAllocOut = 0;
24133 #endif
24134 
24135 
24136 /*
24137 ** Allocate memory that is to be used and released right away.
24138 ** This routine is similar to alloca() in that it is not intended
24139 ** for situations where the memory might be held long-term. This
24140 ** routine is intended to get memory to old large transient data
24141 ** structures that would not normally fit on the stack of an
24142 ** embedded processor.
24143 */
24144 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
24145  void *p;
24146  assert( n>0 );
24147 
24148  sqlite3_mutex_enter(mem0.mutex);
24149  sqlite3StatusHighwater(SQLITE_STATUS_SCRATCH_SIZE, n);
24150  if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
24151  p = mem0.pScratchFree;
24152  mem0.pScratchFree = mem0.pScratchFree->pNext;
24153  mem0.nScratchFree--;
24154  sqlite3StatusUp(SQLITE_STATUS_SCRATCH_USED, 1);
24155  sqlite3_mutex_leave(mem0.mutex);
24156  }else{
24157  sqlite3_mutex_leave(mem0.mutex);
24158  p = sqlite3Malloc(n);
24159  if( sqlite3GlobalConfig.bMemstat && p ){
24160  sqlite3_mutex_enter(mem0.mutex);
24161  sqlite3StatusUp(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p));
24162  sqlite3_mutex_leave(mem0.mutex);
24163  }
24164  sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
24165  }
24166  assert( sqlite3_mutex_notheld(mem0.mutex) );
24167 
24168 
24169 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
24170  /* EVIDENCE-OF: R-12970-05880 SQLite will not use more than one scratch
24171  ** buffers per thread.
24172  **
24173  ** This can only be checked in single-threaded mode.
24174  */
24175  assert( scratchAllocOut==0 );
24176  if( p ) scratchAllocOut++;
24177 #endif
24178 
24179  return p;
24180 }
24181 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
24182  if( p ){
24183 
24184 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
24185  /* Verify that no more than two scratch allocation per thread
24186  ** is outstanding at one time. (This is only checked in the
24187  ** single-threaded case since checking in the multi-threaded case
24188  ** would be much more complicated.) */
24189  assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
24190  scratchAllocOut--;
24191 #endif
24192 
24193  if( SQLITE_WITHIN(p, sqlite3GlobalConfig.pScratch, mem0.pScratchEnd) ){
24194  /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
24195  ScratchFreeslot *pSlot;
24196  pSlot = (ScratchFreeslot*)p;
24197  sqlite3_mutex_enter(mem0.mutex);
24198  pSlot->pNext = mem0.pScratchFree;
24199  mem0.pScratchFree = pSlot;
24200  mem0.nScratchFree++;
24201  assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
24202  sqlite3StatusDown(SQLITE_STATUS_SCRATCH_USED, 1);
24203  sqlite3_mutex_leave(mem0.mutex);
24204  }else{
24205  /* Release memory back to the heap */
24206  assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
24207  assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_SCRATCH) );
24208  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
24209  if( sqlite3GlobalConfig.bMemstat ){
24210  int iSize = sqlite3MallocSize(p);
24211  sqlite3_mutex_enter(mem0.mutex);
24212  sqlite3StatusDown(SQLITE_STATUS_SCRATCH_OVERFLOW, iSize);
24213  sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, iSize);
24214  sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
24215  sqlite3GlobalConfig.m.xFree(p);
24216  sqlite3_mutex_leave(mem0.mutex);
24217  }else{
24218  sqlite3GlobalConfig.m.xFree(p);
24219  }
24220  }
24221  }
24222 }
24223 
24224 /*
24225 ** TRUE if p is a lookaside memory allocation from db
24226 */
24227 #ifndef SQLITE_OMIT_LOOKASIDE
24228 static int isLookaside(sqlite3 *db, void *p){
24229  return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
24230 }
24231 #else
24232 #define isLookaside(A,B) 0
24233 #endif
24234 
24235 /*
24236 ** Return the size of a memory allocation previously obtained from
24237 ** sqlite3Malloc() or sqlite3_malloc().
24238 */
24239 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
24240  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
24241  return sqlite3GlobalConfig.m.xSize(p);
24242 }
24243 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
24244  assert( p!=0 );
24245  if( db==0 || !isLookaside(db,p) ){
24246 #if SQLITE_DEBUG
24247  if( db==0 ){
24248  assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
24249  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
24250  }else{
24251  assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24252  assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24253  }
24254 #endif
24255  return sqlite3GlobalConfig.m.xSize(p);
24256  }else{
24257  assert( sqlite3_mutex_held(db->mutex) );
24258  return db->lookaside.sz;
24259  }
24260 }
24261 SQLITE_API sqlite3_uint64 SQLITE_STDCALL sqlite3_msize(void *p){
24262  assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
24263  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
24264  return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
24265 }
24266 
24267 /*
24268 ** Free memory previously obtained from sqlite3Malloc().
24269 */
24270 SQLITE_API void SQLITE_STDCALL sqlite3_free(void *p){
24271  if( p==0 ) return; /* IMP: R-49053-54554 */
24272  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
24273  assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
24274  if( sqlite3GlobalConfig.bMemstat ){
24275  sqlite3_mutex_enter(mem0.mutex);
24276  sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
24277  sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
24278  sqlite3GlobalConfig.m.xFree(p);
24279  sqlite3_mutex_leave(mem0.mutex);
24280  }else{
24281  sqlite3GlobalConfig.m.xFree(p);
24282  }
24283 }
24284 
24285 /*
24286 ** Add the size of memory allocation "p" to the count in
24287 ** *db->pnBytesFreed.
24288 */
24289 static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
24290  *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
24291 }
24292 
24293 /*
24294 ** Free memory that might be associated with a particular database
24295 ** connection.
24296 */
24297 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
24298  assert( db==0 || sqlite3_mutex_held(db->mutex) );
24299  if( p==0 ) return;
24300  if( db ){
24301  if( db->pnBytesFreed ){
24302  measureAllocationSize(db, p);
24303  return;
24304  }
24305  if( isLookaside(db, p) ){
24306  LookasideSlot *pBuf = (LookasideSlot*)p;
24307 #if SQLITE_DEBUG
24308  /* Trash all content in the buffer being freed */
24309  memset(p, 0xaa, db->lookaside.sz);
24310 #endif
24311  pBuf->pNext = db->lookaside.pFree;
24312  db->lookaside.pFree = pBuf;
24313  db->lookaside.nOut--;
24314  return;
24315  }
24316  }
24317  assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24318  assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24319  assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
24320  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
24321  sqlite3_free(p);
24322 }
24323 
24324 /*
24325 ** Change the size of an existing memory allocation
24326 */
24327 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
24328  int nOld, nNew, nDiff;
24329  void *pNew;
24330  assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
24331  assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
24332  if( pOld==0 ){
24333  return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
24334  }
24335  if( nBytes==0 ){
24336  sqlite3_free(pOld); /* IMP: R-26507-47431 */
24337  return 0;
24338  }
24339  if( nBytes>=0x7fffff00 ){
24340  /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
24341  return 0;
24342  }
24343  nOld = sqlite3MallocSize(pOld);
24344  /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
24345  ** argument to xRealloc is always a value returned by a prior call to
24346  ** xRoundup. */
24347  nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
24348  if( nOld==nNew ){
24349  pNew = pOld;
24350  }else if( sqlite3GlobalConfig.bMemstat ){
24351  sqlite3_mutex_enter(mem0.mutex);
24352  sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
24353  nDiff = nNew - nOld;
24354  if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
24355  mem0.alarmThreshold-nDiff ){
24356  sqlite3MallocAlarm(nDiff);
24357  }
24358  pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
24359  if( pNew==0 && mem0.alarmThreshold>0 ){
24360  sqlite3MallocAlarm((int)nBytes);
24361  pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
24362  }
24363  if( pNew ){
24364  nNew = sqlite3MallocSize(pNew);
24365  sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
24366  }
24367  sqlite3_mutex_leave(mem0.mutex);
24368  }else{
24369  pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
24370  }
24371  assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
24372  return pNew;
24373 }
24374 
24375 /*
24376 ** The public interface to sqlite3Realloc. Make sure that the memory
24377 ** subsystem is initialized prior to invoking sqliteRealloc.
24378 */
24379 SQLITE_API void *SQLITE_STDCALL sqlite3_realloc(void *pOld, int n){
24380 #ifndef SQLITE_OMIT_AUTOINIT
24381  if( sqlite3_initialize() ) return 0;
24382 #endif
24383  if( n<0 ) n = 0; /* IMP: R-26507-47431 */
24384  return sqlite3Realloc(pOld, n);
24385 }
24386 SQLITE_API void *SQLITE_STDCALL sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
24387 #ifndef SQLITE_OMIT_AUTOINIT
24388  if( sqlite3_initialize() ) return 0;
24389 #endif
24390  return sqlite3Realloc(pOld, n);
24391 }
24392 
24393 
24394 /*
24395 ** Allocate and zero memory.
24396 */
24397 SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
24398  void *p = sqlite3Malloc(n);
24399  if( p ){
24400  memset(p, 0, (size_t)n);
24401  }
24402  return p;
24403 }
24404 
24405 /*
24406 ** Allocate and zero memory. If the allocation fails, make
24407 ** the mallocFailed flag in the connection pointer.
24408 */
24409 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
24410  void *p;
24411  testcase( db==0 );
24412  p = sqlite3DbMallocRaw(db, n);
24413  if( p ) memset(p, 0, (size_t)n);
24414  return p;
24415 }
24416 
24417 
24418 /* Finish the work of sqlite3DbMallocRawNN for the unusual and
24419 ** slower case when the allocation cannot be fulfilled using lookaside.
24420 */
24421 static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
24422  void *p;
24423  assert( db!=0 );
24424  p = sqlite3Malloc(n);
24425  if( !p ) sqlite3OomFault(db);
24426  sqlite3MemdebugSetType(p,
24427  (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
24428  return p;
24429 }
24430 
24431 /*
24432 ** Allocate memory, either lookaside (if possible) or heap.
24433 ** If the allocation fails, set the mallocFailed flag in
24434 ** the connection pointer.
24435 **
24436 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
24437 ** failure on the same database connection) then always return 0.
24438 ** Hence for a particular database connection, once malloc starts
24439 ** failing, it fails consistently until mallocFailed is reset.
24440 ** This is an important assumption. There are many places in the
24441 ** code that do things like this:
24442 **
24443 ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
24444 ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
24445 ** if( b ) a[10] = 9;
24446 **
24447 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
24448 ** that all prior mallocs (ex: "a") worked too.
24449 **
24450 ** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
24451 ** not a NULL pointer.
24452 */
24453 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
24454  void *p;
24455  if( db ) return sqlite3DbMallocRawNN(db, n);
24456  p = sqlite3Malloc(n);
24457  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
24458  return p;
24459 }
24460 SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
24461 #ifndef SQLITE_OMIT_LOOKASIDE
24462  LookasideSlot *pBuf;
24463  assert( db!=0 );
24464  assert( sqlite3_mutex_held(db->mutex) );
24465  assert( db->pnBytesFreed==0 );
24466  if( db->lookaside.bDisable==0 ){
24467  assert( db->mallocFailed==0 );
24468  if( n>db->lookaside.sz ){
24469  db->lookaside.anStat[1]++;
24470  }else if( (pBuf = db->lookaside.pFree)==0 ){
24471  db->lookaside.anStat[2]++;
24472  }else{
24473  db->lookaside.pFree = pBuf->pNext;
24474  db->lookaside.nOut++;
24475  db->lookaside.anStat[0]++;
24476  if( db->lookaside.nOut>db->lookaside.mxOut ){
24477  db->lookaside.mxOut = db->lookaside.nOut;
24478  }
24479  return (void*)pBuf;
24480  }
24481  }else if( db->mallocFailed ){
24482  return 0;
24483  }
24484 #else
24485  assert( db!=0 );
24486  assert( sqlite3_mutex_held(db->mutex) );
24487  assert( db->pnBytesFreed==0 );
24488  if( db->mallocFailed ){
24489  return 0;
24490  }
24491 #endif
24492  return dbMallocRawFinish(db, n);
24493 }
24494 
24495 /* Forward declaration */
24496 static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
24497 
24498 /*
24499 ** Resize the block of memory pointed to by p to n bytes. If the
24500 ** resize fails, set the mallocFailed flag in the connection object.
24501 */
24502 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
24503  assert( db!=0 );
24504  if( p==0 ) return sqlite3DbMallocRawNN(db, n);
24505  assert( sqlite3_mutex_held(db->mutex) );
24506  if( isLookaside(db,p) && n<=db->lookaside.sz ) return p;
24507  return dbReallocFinish(db, p, n);
24508 }
24509 static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
24510  void *pNew = 0;
24511  assert( db!=0 );
24512  assert( p!=0 );
24513  if( db->mallocFailed==0 ){
24514  if( isLookaside(db, p) ){
24515  pNew = sqlite3DbMallocRawNN(db, n);
24516  if( pNew ){
24517  memcpy(pNew, p, db->lookaside.sz);
24518  sqlite3DbFree(db, p);
24519  }
24520  }else{
24521  assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24522  assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24523  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
24524  pNew = sqlite3_realloc64(p, n);
24525  if( !pNew ){
24526  sqlite3OomFault(db);
24527  }
24528  sqlite3MemdebugSetType(pNew,
24529  (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
24530  }
24531  }
24532  return pNew;
24533 }
24534 
24535 /*
24536 ** Attempt to reallocate p. If the reallocation fails, then free p
24537 ** and set the mallocFailed flag in the database connection.
24538 */
24539 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
24540  void *pNew;
24541  pNew = sqlite3DbRealloc(db, p, n);
24542  if( !pNew ){
24543  sqlite3DbFree(db, p);
24544  }
24545  return pNew;
24546 }
24547 
24548 /*
24549 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
24550 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
24551 ** is because when memory debugging is turned on, these two functions are
24552 ** called via macros that record the current file and line number in the
24553 ** ThreadData structure.
24554 */
24555 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
24556  char *zNew;
24557  size_t n;
24558  if( z==0 ){
24559  return 0;
24560  }
24561  n = sqlite3Strlen30(z) + 1;
24562  assert( (n&0x7fffffff)==n );
24563  zNew = sqlite3DbMallocRaw(db, (int)n);
24564  if( zNew ){
24565  memcpy(zNew, z, n);
24566  }
24567  return zNew;
24568 }
24569 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
24570  char *zNew;
24571  assert( db!=0 );
24572  if( z==0 ){
24573  return 0;
24574  }
24575  assert( (n&0x7fffffff)==n );
24576  zNew = sqlite3DbMallocRawNN(db, n+1);
24577  if( zNew ){
24578  memcpy(zNew, z, (size_t)n);
24579  zNew[n] = 0;
24580  }
24581  return zNew;
24582 }
24583 
24584 /*
24585 ** Free any prior content in *pz and replace it with a copy of zNew.
24586 */
24587 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
24588  sqlite3DbFree(db, *pz);
24589  *pz = sqlite3DbStrDup(db, zNew);
24590 }
24591 
24592 /*
24593 ** Call this routine to record the fact that an OOM (out-of-memory) error
24594 ** has happened. This routine will set db->mallocFailed, and also
24595 ** temporarily disable the lookaside memory allocator and interrupt
24596 ** any running VDBEs.
24597 */
24598 SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
24599  if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
24600  db->mallocFailed = 1;
24601  if( db->nVdbeExec>0 ){
24602  db->u1.isInterrupted = 1;
24603  }
24604  db->lookaside.bDisable++;
24605  }
24606 }
24607 
24608 /*
24609 ** This routine reactivates the memory allocator and clears the
24610 ** db->mallocFailed flag as necessary.
24611 **
24612 ** The memory allocator is not restarted if there are running
24613 ** VDBEs.
24614 */
24615 SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){
24616  if( db->mallocFailed && db->nVdbeExec==0 ){
24617  db->mallocFailed = 0;
24618  db->u1.isInterrupted = 0;
24619  assert( db->lookaside.bDisable>0 );
24620  db->lookaside.bDisable--;
24621  }
24622 }
24623 
24624 /*
24625 ** Take actions at the end of an API call to indicate an OOM error
24626 */
24627 static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
24628  sqlite3OomClear(db);
24629  sqlite3Error(db, SQLITE_NOMEM);
24630  return SQLITE_NOMEM_BKPT;
24631 }
24632 
24633 /*
24634 ** This function must be called before exiting any API function (i.e.
24635 ** returning control to the user) that has called sqlite3_malloc or
24636 ** sqlite3_realloc.
24637 **
24638 ** The returned value is normally a copy of the second argument to this
24639 ** function. However, if a malloc() failure has occurred since the previous
24640 ** invocation SQLITE_NOMEM is returned instead.
24641 **
24642 ** If an OOM as occurred, then the connection error-code (the value
24643 ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
24644 */
24645 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
24646  /* If the db handle must hold the connection handle mutex here.
24647  ** Otherwise the read (and possible write) of db->mallocFailed
24648  ** is unsafe, as is the call to sqlite3Error().
24649  */
24650  assert( db!=0 );
24651  assert( sqlite3_mutex_held(db->mutex) );
24652  if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
24653  return apiOomError(db);
24654  }
24655  return rc & db->errMask;
24656 }
24657 
24658 /************** End of malloc.c **********************************************/
24659 /************** Begin file printf.c ******************************************/
24660 /*
24661 ** The "printf" code that follows dates from the 1980's. It is in
24662 ** the public domain.
24663 **
24664 **************************************************************************
24665 **
24666 ** This file contains code for a set of "printf"-like routines. These
24667 ** routines format strings much like the printf() from the standard C
24668 ** library, though the implementation here has enhancements to support
24669 ** SQLite.
24670 */
24671 /* #include "sqliteInt.h" */
24672 
24673 /*
24674 ** Conversion types fall into various categories as defined by the
24675 ** following enumeration.
24676 */
24677 #define etRADIX 0 /* Integer types. %d, %x, %o, and so forth */
24678 #define etFLOAT 1 /* Floating point. %f */
24679 #define etEXP 2 /* Exponentional notation. %e and %E */
24680 #define etGENERIC 3 /* Floating or exponential, depending on exponent. %g */
24681 #define etSIZE 4 /* Return number of characters processed so far. %n */
24682 #define etSTRING 5 /* Strings. %s */
24683 #define etDYNSTRING 6 /* Dynamically allocated strings. %z */
24684 #define etPERCENT 7 /* Percent symbol. %% */
24685 #define etCHARX 8 /* Characters. %c */
24686 /* The rest are extensions, not normally found in printf() */
24687 #define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */
24688 #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
24689  NULL pointers replaced by SQL NULL. %Q */
24690 #define etTOKEN 11 /* a pointer to a Token structure */
24691 #define etSRCLIST 12 /* a pointer to a SrcList */
24692 #define etPOINTER 13 /* The %p conversion */
24693 #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
24694 #define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
24695 
24696 #define etINVALID 16 /* Any unrecognized conversion type */
24697 
24698 
24699 /*
24700 ** An "etByte" is an 8-bit unsigned value.
24701 */
24702 typedef unsigned char etByte;
24703 
24704 /*
24705 ** Each builtin conversion character (ex: the 'd' in "%d") is described
24706 ** by an instance of the following structure
24707 */
24708 typedef struct et_info { /* Information about each format field */
24709  char fmttype; /* The format field code letter */
24710  etByte base; /* The base for radix conversion */
24711  etByte flags; /* One or more of FLAG_ constants below */
24712  etByte type; /* Conversion paradigm */
24713  etByte charset; /* Offset into aDigits[] of the digits string */
24714  etByte prefix; /* Offset into aPrefix[] of the prefix string */
24715 } et_info;
24716 
24717 /*
24718 ** Allowed values for et_info.flags
24719 */
24720 #define FLAG_SIGNED 1 /* True if the value to convert is signed */
24721 #define FLAG_INTERN 2 /* True if for internal use only */
24722 #define FLAG_STRING 4 /* Allow infinity precision */
24723 
24724 
24725 /*
24726 ** The following table is searched linearly, so it is good to put the
24727 ** most frequently used conversion types first.
24728 */
24729 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
24730 static const char aPrefix[] = "-x0\000X0";
24731 static const et_info fmtinfo[] = {
24732  { 'd', 10, 1, etRADIX, 0, 0 },
24733  { 's', 0, 4, etSTRING, 0, 0 },
24734  { 'g', 0, 1, etGENERIC, 30, 0 },
24735  { 'z', 0, 4, etDYNSTRING, 0, 0 },
24736  { 'q', 0, 4, etSQLESCAPE, 0, 0 },
24737  { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
24738  { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
24739  { 'c', 0, 0, etCHARX, 0, 0 },
24740  { 'o', 8, 0, etRADIX, 0, 2 },
24741  { 'u', 10, 0, etRADIX, 0, 0 },
24742  { 'x', 16, 0, etRADIX, 16, 1 },
24743  { 'X', 16, 0, etRADIX, 0, 4 },
24744 #ifndef SQLITE_OMIT_FLOATING_POINT
24745  { 'f', 0, 1, etFLOAT, 0, 0 },
24746  { 'e', 0, 1, etEXP, 30, 0 },
24747  { 'E', 0, 1, etEXP, 14, 0 },
24748  { 'G', 0, 1, etGENERIC, 14, 0 },
24749 #endif
24750  { 'i', 10, 1, etRADIX, 0, 0 },
24751  { 'n', 0, 0, etSIZE, 0, 0 },
24752  { '%', 0, 0, etPERCENT, 0, 0 },
24753  { 'p', 16, 0, etPOINTER, 0, 1 },
24754 
24755 /* All the rest have the FLAG_INTERN bit set and are thus for internal
24756 ** use only */
24757  { 'T', 0, 2, etTOKEN, 0, 0 },
24758  { 'S', 0, 2, etSRCLIST, 0, 0 },
24759  { 'r', 10, 3, etORDINAL, 0, 0 },
24760 };
24761 
24762 /*
24763 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
24764 ** conversions will work.
24765 */
24766 #ifndef SQLITE_OMIT_FLOATING_POINT
24767 /*
24768 ** "*val" is a double such that 0.1 <= *val < 10.0
24769 ** Return the ascii code for the leading digit of *val, then
24770 ** multiply "*val" by 10.0 to renormalize.
24771 **
24772 ** Example:
24773 ** input: *val = 3.14159
24774 ** output: *val = 1.4159 function return = '3'
24775 **
24776 ** The counter *cnt is incremented each time. After counter exceeds
24777 ** 16 (the number of significant digits in a 64-bit float) '0' is
24778 ** always returned.
24779 */
24780 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
24781  int digit;
24782  LONGDOUBLE_TYPE d;
24783  if( (*cnt)<=0 ) return '0';
24784  (*cnt)--;
24785  digit = (int)*val;
24786  d = digit;
24787  digit += '0';
24788  *val = (*val - d)*10.0;
24789  return (char)digit;
24790 }
24791 #endif /* SQLITE_OMIT_FLOATING_POINT */
24792 
24793 /*
24794 ** Set the StrAccum object to an error mode.
24795 */
24796 static void setStrAccumError(StrAccum *p, u8 eError){
24797  assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG );
24798  p->accError = eError;
24799  p->nAlloc = 0;
24800 }
24801 
24802 /*
24803 ** Extra argument values from a PrintfArguments object
24804 */
24805 static sqlite3_int64 getIntArg(PrintfArguments *p){
24806  if( p->nArg<=p->nUsed ) return 0;
24807  return sqlite3_value_int64(p->apArg[p->nUsed++]);
24808 }
24809 static double getDoubleArg(PrintfArguments *p){
24810  if( p->nArg<=p->nUsed ) return 0.0;
24811  return sqlite3_value_double(p->apArg[p->nUsed++]);
24812 }
24813 static char *getTextArg(PrintfArguments *p){
24814  if( p->nArg<=p->nUsed ) return 0;
24815  return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
24816 }
24817 
24818 
24819 /*
24820 ** On machines with a small stack size, you can redefine the
24821 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
24822 */
24823 #ifndef SQLITE_PRINT_BUF_SIZE
24824 # define SQLITE_PRINT_BUF_SIZE 70
24825 #endif
24826 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
24827 
24828 /*
24829 ** Render a string given by "fmt" into the StrAccum object.
24830 */
24831 SQLITE_PRIVATE void sqlite3VXPrintf(
24832  StrAccum *pAccum, /* Accumulate results here */
24833  const char *fmt, /* Format string */
24834  va_list ap /* arguments */
24835 ){
24836  int c; /* Next character in the format string */
24837  char *bufpt; /* Pointer to the conversion buffer */
24838  int precision; /* Precision of the current field */
24839  int length; /* Length of the field */
24840  int idx; /* A general purpose loop counter */
24841  int width; /* Width of the current field */
24842  etByte flag_leftjustify; /* True if "-" flag is present */
24843  etByte flag_plussign; /* True if "+" flag is present */
24844  etByte flag_blanksign; /* True if " " flag is present */
24845  etByte flag_alternateform; /* True if "#" flag is present */
24846  etByte flag_altform2; /* True if "!" flag is present */
24847  etByte flag_zeropad; /* True if field width constant starts with zero */
24848  etByte flag_long; /* True if "l" flag is present */
24849  etByte flag_longlong; /* True if the "ll" flag is present */
24850  etByte done; /* Loop termination flag */
24851  etByte xtype = etINVALID; /* Conversion paradigm */
24852  u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
24853  u8 useIntern; /* Ok to use internal conversions (ex: %T) */
24854  char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
24855  sqlite_uint64 longvalue; /* Value for integer types */
24856  LONGDOUBLE_TYPE realvalue; /* Value for real types */
24857  const et_info *infop; /* Pointer to the appropriate info structure */
24858  char *zOut; /* Rendering buffer */
24859  int nOut; /* Size of the rendering buffer */
24860  char *zExtra = 0; /* Malloced memory used by some conversion */
24861 #ifndef SQLITE_OMIT_FLOATING_POINT
24862  int exp, e2; /* exponent of real numbers */
24863  int nsd; /* Number of significant digits returned */
24864  double rounder; /* Used for rounding floating point values */
24865  etByte flag_dp; /* True if decimal point should be shown */
24866  etByte flag_rtz; /* True if trailing zeros should be removed */
24867 #endif
24868  PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
24869  char buf[etBUFSIZE]; /* Conversion buffer */
24870 
24871  bufpt = 0;
24872  if( pAccum->printfFlags ){
24873  if( (bArgList = (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){
24874  pArgList = va_arg(ap, PrintfArguments*);
24875  }
24876  useIntern = pAccum->printfFlags & SQLITE_PRINTF_INTERNAL;
24877  }else{
24878  bArgList = useIntern = 0;
24879  }
24880  for(; (c=(*fmt))!=0; ++fmt){
24881  if( c!='%' ){
24882  bufpt = (char *)fmt;
24883 #if HAVE_STRCHRNUL
24884  fmt = strchrnul(fmt, '%');
24885 #else
24886  do{ fmt++; }while( *fmt && *fmt != '%' );
24887 #endif
24888  sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
24889  if( *fmt==0 ) break;
24890  }
24891  if( (c=(*++fmt))==0 ){
24892  sqlite3StrAccumAppend(pAccum, "%", 1);
24893  break;
24894  }
24895  /* Find out what flags are present */
24896  flag_leftjustify = flag_plussign = flag_blanksign =
24897  flag_alternateform = flag_altform2 = flag_zeropad = 0;
24898  done = 0;
24899  do{
24900  switch( c ){
24901  case '-': flag_leftjustify = 1; break;
24902  case '+': flag_plussign = 1; break;
24903  case ' ': flag_blanksign = 1; break;
24904  case '#': flag_alternateform = 1; break;
24905  case '!': flag_altform2 = 1; break;
24906  case '0': flag_zeropad = 1; break;
24907  default: done = 1; break;
24908  }
24909  }while( !done && (c=(*++fmt))!=0 );
24910  /* Get the field width */
24911  if( c=='*' ){
24912  if( bArgList ){
24913  width = (int)getIntArg(pArgList);
24914  }else{
24915  width = va_arg(ap,int);
24916  }
24917  if( width<0 ){
24918  flag_leftjustify = 1;
24919  width = width >= -2147483647 ? -width : 0;
24920  }
24921  c = *++fmt;
24922  }else{
24923  unsigned wx = 0;
24924  while( c>='0' && c<='9' ){
24925  wx = wx*10 + c - '0';
24926  c = *++fmt;
24927  }
24928  testcase( wx>0x7fffffff );
24929  width = wx & 0x7fffffff;
24930  }
24931  assert( width>=0 );
24932 #ifdef SQLITE_PRINTF_PRECISION_LIMIT
24933  if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
24934  width = SQLITE_PRINTF_PRECISION_LIMIT;
24935  }
24936 #endif
24937 
24938  /* Get the precision */
24939  if( c=='.' ){
24940  c = *++fmt;
24941  if( c=='*' ){
24942  if( bArgList ){
24943  precision = (int)getIntArg(pArgList);
24944  }else{
24945  precision = va_arg(ap,int);
24946  }
24947  c = *++fmt;
24948  if( precision<0 ){
24949  precision = precision >= -2147483647 ? -precision : -1;
24950  }
24951  }else{
24952  unsigned px = 0;
24953  while( c>='0' && c<='9' ){
24954  px = px*10 + c - '0';
24955  c = *++fmt;
24956  }
24957  testcase( px>0x7fffffff );
24958  precision = px & 0x7fffffff;
24959  }
24960  }else{
24961  precision = -1;
24962  }
24963  assert( precision>=(-1) );
24964 #ifdef SQLITE_PRINTF_PRECISION_LIMIT
24965  if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
24966  precision = SQLITE_PRINTF_PRECISION_LIMIT;
24967  }
24968 #endif
24969 
24970 
24971  /* Get the conversion type modifier */
24972  if( c=='l' ){
24973  flag_long = 1;
24974  c = *++fmt;
24975  if( c=='l' ){
24976  flag_longlong = 1;
24977  c = *++fmt;
24978  }else{
24979  flag_longlong = 0;
24980  }
24981  }else{
24982  flag_long = flag_longlong = 0;
24983  }
24984  /* Fetch the info entry for the field */
24985  infop = &fmtinfo[0];
24986  xtype = etINVALID;
24987  for(idx=0; idx<ArraySize(fmtinfo); idx++){
24988  if( c==fmtinfo[idx].fmttype ){
24989  infop = &fmtinfo[idx];
24990  if( useIntern || (infop->flags & FLAG_INTERN)==0 ){
24991  xtype = infop->type;
24992  }else{
24993  return;
24994  }
24995  break;
24996  }
24997  }
24998 
24999  /*
25000  ** At this point, variables are initialized as follows:
25001  **
25002  ** flag_alternateform TRUE if a '#' is present.
25003  ** flag_altform2 TRUE if a '!' is present.
25004  ** flag_plussign TRUE if a '+' is present.
25005  ** flag_leftjustify TRUE if a '-' is present or if the
25006  ** field width was negative.
25007  ** flag_zeropad TRUE if the width began with 0.
25008  ** flag_long TRUE if the letter 'l' (ell) prefixed
25009  ** the conversion character.
25010  ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
25011  ** the conversion character.
25012  ** flag_blanksign TRUE if a ' ' is present.
25013  ** width The specified field width. This is
25014  ** always non-negative. Zero is the default.
25015  ** precision The specified precision. The default
25016  ** is -1.
25017  ** xtype The class of the conversion.
25018  ** infop Pointer to the appropriate info struct.
25019  */
25020  switch( xtype ){
25021  case etPOINTER:
25022  flag_longlong = sizeof(char*)==sizeof(i64);
25023  flag_long = sizeof(char*)==sizeof(long int);
25024  /* Fall through into the next case */
25025  case etORDINAL:
25026  case etRADIX:
25027  if( infop->flags & FLAG_SIGNED ){
25028  i64 v;
25029  if( bArgList ){
25030  v = getIntArg(pArgList);
25031  }else if( flag_longlong ){
25032  v = va_arg(ap,i64);
25033  }else if( flag_long ){
25034  v = va_arg(ap,long int);
25035  }else{
25036  v = va_arg(ap,int);
25037  }
25038  if( v<0 ){
25039  if( v==SMALLEST_INT64 ){
25040  longvalue = ((u64)1)<<63;
25041  }else{
25042  longvalue = -v;
25043  }
25044  prefix = '-';
25045  }else{
25046  longvalue = v;
25047  if( flag_plussign ) prefix = '+';
25048  else if( flag_blanksign ) prefix = ' ';
25049  else prefix = 0;
25050  }
25051  }else{
25052  if( bArgList ){
25053  longvalue = (u64)getIntArg(pArgList);
25054  }else if( flag_longlong ){
25055  longvalue = va_arg(ap,u64);
25056  }else if( flag_long ){
25057  longvalue = va_arg(ap,unsigned long int);
25058  }else{
25059  longvalue = va_arg(ap,unsigned int);
25060  }
25061  prefix = 0;
25062  }
25063  if( longvalue==0 ) flag_alternateform = 0;
25064  if( flag_zeropad && precision<width-(prefix!=0) ){
25065  precision = width-(prefix!=0);
25066  }
25067  if( precision<etBUFSIZE-10 ){
25068  nOut = etBUFSIZE;
25069  zOut = buf;
25070  }else{
25071  nOut = precision + 10;
25072  zOut = zExtra = sqlite3Malloc( nOut );
25073  if( zOut==0 ){
25074  setStrAccumError(pAccum, STRACCUM_NOMEM);
25075  return;
25076  }
25077  }
25078  bufpt = &zOut[nOut-1];
25079  if( xtype==etORDINAL ){
25080  static const char zOrd[] = "thstndrd";
25081  int x = (int)(longvalue % 10);
25082  if( x>=4 || (longvalue/10)%10==1 ){
25083  x = 0;
25084  }
25085  *(--bufpt) = zOrd[x*2+1];
25086  *(--bufpt) = zOrd[x*2];
25087  }
25088  {
25089  const char *cset = &aDigits[infop->charset];
25090  u8 base = infop->base;
25091  do{ /* Convert to ascii */
25092  *(--bufpt) = cset[longvalue%base];
25093  longvalue = longvalue/base;
25094  }while( longvalue>0 );
25095  }
25096  length = (int)(&zOut[nOut-1]-bufpt);
25097  for(idx=precision-length; idx>0; idx--){
25098  *(--bufpt) = '0'; /* Zero pad */
25099  }
25100  if( prefix ) *(--bufpt) = prefix; /* Add sign */
25101  if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
25102  const char *pre;
25103  char x;
25104  pre = &aPrefix[infop->prefix];
25105  for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
25106  }
25107  length = (int)(&zOut[nOut-1]-bufpt);
25108  break;
25109  case etFLOAT:
25110  case etEXP:
25111  case etGENERIC:
25112  if( bArgList ){
25113  realvalue = getDoubleArg(pArgList);
25114  }else{
25115  realvalue = va_arg(ap,double);
25116  }
25117 #ifdef SQLITE_OMIT_FLOATING_POINT
25118  length = 0;
25119 #else
25120  if( precision<0 ) precision = 6; /* Set default precision */
25121  if( realvalue<0.0 ){
25122  realvalue = -realvalue;
25123  prefix = '-';
25124  }else{
25125  if( flag_plussign ) prefix = '+';
25126  else if( flag_blanksign ) prefix = ' ';
25127  else prefix = 0;
25128  }
25129  if( xtype==etGENERIC && precision>0 ) precision--;
25130  testcase( precision>0xfff );
25131  for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
25132  if( xtype==etFLOAT ) realvalue += rounder;
25133  /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
25134  exp = 0;
25135  if( sqlite3IsNaN((double)realvalue) ){
25136  bufpt = "NaN";
25137  length = 3;
25138  break;
25139  }
25140  if( realvalue>0.0 ){
25141  LONGDOUBLE_TYPE scale = 1.0;
25142  while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
25143  while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
25144  while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
25145  realvalue /= scale;
25146  while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
25147  while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
25148  if( exp>350 ){
25149  bufpt = buf;
25150  buf[0] = prefix;
25151  memcpy(buf+(prefix!=0),"Inf",4);
25152  length = 3+(prefix!=0);
25153  break;
25154  }
25155  }
25156  bufpt = buf;
25157  /*
25158  ** If the field type is etGENERIC, then convert to either etEXP
25159  ** or etFLOAT, as appropriate.
25160  */
25161  if( xtype!=etFLOAT ){
25162  realvalue += rounder;
25163  if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
25164  }
25165  if( xtype==etGENERIC ){
25166  flag_rtz = !flag_alternateform;
25167  if( exp<-4 || exp>precision ){
25168  xtype = etEXP;
25169  }else{
25170  precision = precision - exp;
25171  xtype = etFLOAT;
25172  }
25173  }else{
25174  flag_rtz = flag_altform2;
25175  }
25176  if( xtype==etEXP ){
25177  e2 = 0;
25178  }else{
25179  e2 = exp;
25180  }
25181  if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
25182  bufpt = zExtra
25183  = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
25184  if( bufpt==0 ){
25185  setStrAccumError(pAccum, STRACCUM_NOMEM);
25186  return;
25187  }
25188  }
25189  zOut = bufpt;
25190  nsd = 16 + flag_altform2*10;
25191  flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
25192  /* The sign in front of the number */
25193  if( prefix ){
25194  *(bufpt++) = prefix;
25195  }
25196  /* Digits prior to the decimal point */
25197  if( e2<0 ){
25198  *(bufpt++) = '0';
25199  }else{
25200  for(; e2>=0; e2--){
25201  *(bufpt++) = et_getdigit(&realvalue,&nsd);
25202  }
25203  }
25204  /* The decimal point */
25205  if( flag_dp ){
25206  *(bufpt++) = '.';
25207  }
25208  /* "0" digits after the decimal point but before the first
25209  ** significant digit of the number */
25210  for(e2++; e2<0; precision--, e2++){
25211  assert( precision>0 );
25212  *(bufpt++) = '0';
25213  }
25214  /* Significant digits after the decimal point */
25215  while( (precision--)>0 ){
25216  *(bufpt++) = et_getdigit(&realvalue,&nsd);
25217  }
25218  /* Remove trailing zeros and the "." if no digits follow the "." */
25219  if( flag_rtz && flag_dp ){
25220  while( bufpt[-1]=='0' ) *(--bufpt) = 0;
25221  assert( bufpt>zOut );
25222  if( bufpt[-1]=='.' ){
25223  if( flag_altform2 ){
25224  *(bufpt++) = '0';
25225  }else{
25226  *(--bufpt) = 0;
25227  }
25228  }
25229  }
25230  /* Add the "eNNN" suffix */
25231  if( xtype==etEXP ){
25232  *(bufpt++) = aDigits[infop->charset];
25233  if( exp<0 ){
25234  *(bufpt++) = '-'; exp = -exp;
25235  }else{
25236  *(bufpt++) = '+';
25237  }
25238  if( exp>=100 ){
25239  *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
25240  exp %= 100;
25241  }
25242  *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
25243  *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
25244  }
25245  *bufpt = 0;
25246 
25247  /* The converted number is in buf[] and zero terminated. Output it.
25248  ** Note that the number is in the usual order, not reversed as with
25249  ** integer conversions. */
25250  length = (int)(bufpt-zOut);
25251  bufpt = zOut;
25252 
25253  /* Special case: Add leading zeros if the flag_zeropad flag is
25254  ** set and we are not left justified */
25255  if( flag_zeropad && !flag_leftjustify && length < width){
25256  int i;
25257  int nPad = width - length;
25258  for(i=width; i>=nPad; i--){
25259  bufpt[i] = bufpt[i-nPad];
25260  }
25261  i = prefix!=0;
25262  while( nPad-- ) bufpt[i++] = '0';
25263  length = width;
25264  }
25265 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
25266  break;
25267  case etSIZE:
25268  if( !bArgList ){
25269  *(va_arg(ap,int*)) = pAccum->nChar;
25270  }
25271  length = width = 0;
25272  break;
25273  case etPERCENT:
25274  buf[0] = '%';
25275  bufpt = buf;
25276  length = 1;
25277  break;
25278  case etCHARX:
25279  if( bArgList ){
25280  bufpt = getTextArg(pArgList);
25281  c = bufpt ? bufpt[0] : 0;
25282  }else{
25283  c = va_arg(ap,int);
25284  }
25285  if( precision>1 ){
25286  width -= precision-1;
25287  if( width>1 && !flag_leftjustify ){
25288  sqlite3AppendChar(pAccum, width-1, ' ');
25289  width = 0;
25290  }
25291  sqlite3AppendChar(pAccum, precision-1, c);
25292  }
25293  length = 1;
25294  buf[0] = c;
25295  bufpt = buf;
25296  break;
25297  case etSTRING:
25298  case etDYNSTRING:
25299  if( bArgList ){
25300  bufpt = getTextArg(pArgList);
25301  xtype = etSTRING;
25302  }else{
25303  bufpt = va_arg(ap,char*);
25304  }
25305  if( bufpt==0 ){
25306  bufpt = "";
25307  }else if( xtype==etDYNSTRING ){
25308  zExtra = bufpt;
25309  }
25310  if( precision>=0 ){
25311  for(length=0; length<precision && bufpt[length]; length++){}
25312  }else{
25313  length = sqlite3Strlen30(bufpt);
25314  }
25315  break;
25316  case etSQLESCAPE: /* Escape ' characters */
25317  case etSQLESCAPE2: /* Escape ' and enclose in '...' */
25318  case etSQLESCAPE3: { /* Escape " characters */
25319  int i, j, k, n, isnull;
25320  int needQuote;
25321  char ch;
25322  char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
25323  char *escarg;
25324 
25325  if( bArgList ){
25326  escarg = getTextArg(pArgList);
25327  }else{
25328  escarg = va_arg(ap,char*);
25329  }
25330  isnull = escarg==0;
25331  if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
25332  k = precision;
25333  for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
25334  if( ch==q ) n++;
25335  }
25336  needQuote = !isnull && xtype==etSQLESCAPE2;
25337  n += i + 3;
25338  if( n>etBUFSIZE ){
25339  bufpt = zExtra = sqlite3Malloc( n );
25340  if( bufpt==0 ){
25341  setStrAccumError(pAccum, STRACCUM_NOMEM);
25342  return;
25343  }
25344  }else{
25345  bufpt = buf;
25346  }
25347  j = 0;
25348  if( needQuote ) bufpt[j++] = q;
25349  k = i;
25350  for(i=0; i<k; i++){
25351  bufpt[j++] = ch = escarg[i];
25352  if( ch==q ) bufpt[j++] = ch;
25353  }
25354  if( needQuote ) bufpt[j++] = q;
25355  bufpt[j] = 0;
25356  length = j;
25357  /* The precision in %q and %Q means how many input characters to
25358  ** consume, not the length of the output...
25359  ** if( precision>=0 && precision<length ) length = precision; */
25360  break;
25361  }
25362  case etTOKEN: {
25363  Token *pToken = va_arg(ap, Token*);
25364  assert( bArgList==0 );
25365  if( pToken && pToken->n ){
25366  sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
25367  }
25368  length = width = 0;
25369  break;
25370  }
25371  case etSRCLIST: {
25372  SrcList *pSrc = va_arg(ap, SrcList*);
25373  int k = va_arg(ap, int);
25374  struct SrcList_item *pItem = &pSrc->a[k];
25375  assert( bArgList==0 );
25376  assert( k>=0 && k<pSrc->nSrc );
25377  if( pItem->zDatabase ){
25378  sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
25379  sqlite3StrAccumAppend(pAccum, ".", 1);
25380  }
25381  sqlite3StrAccumAppendAll(pAccum, pItem->zName);
25382  length = width = 0;
25383  break;
25384  }
25385  default: {
25386  assert( xtype==etINVALID );
25387  return;
25388  }
25389  }/* End switch over the format type */
25390  /*
25391  ** The text of the conversion is pointed to by "bufpt" and is
25392  ** "length" characters long. The field width is "width". Do
25393  ** the output.
25394  */
25395  width -= length;
25396  if( width>0 && !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
25397  sqlite3StrAccumAppend(pAccum, bufpt, length);
25398  if( width>0 && flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
25399 
25400  if( zExtra ){
25401  sqlite3DbFree(pAccum->db, zExtra);
25402  zExtra = 0;
25403  }
25404  }/* End for loop over the format string */
25405 } /* End of function */
25406 
25407 /*
25408 ** Enlarge the memory allocation on a StrAccum object so that it is
25409 ** able to accept at least N more bytes of text.
25410 **
25411 ** Return the number of bytes of text that StrAccum is able to accept
25412 ** after the attempted enlargement. The value returned might be zero.
25413 */
25414 static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
25415  char *zNew;
25416  assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
25417  if( p->accError ){
25418  testcase(p->accError==STRACCUM_TOOBIG);
25419  testcase(p->accError==STRACCUM_NOMEM);
25420  return 0;
25421  }
25422  if( p->mxAlloc==0 ){
25423  N = p->nAlloc - p->nChar - 1;
25424  setStrAccumError(p, STRACCUM_TOOBIG);
25425  return N;
25426  }else{
25427  char *zOld = isMalloced(p) ? p->zText : 0;
25428  i64 szNew = p->nChar;
25429  assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
25430  szNew += N + 1;
25431  if( szNew+p->nChar<=p->mxAlloc ){
25432  /* Force exponential buffer size growth as long as it does not overflow,
25433  ** to avoid having to call this routine too often */
25434  szNew += p->nChar;
25435  }
25436  if( szNew > p->mxAlloc ){
25437  sqlite3StrAccumReset(p);
25438  setStrAccumError(p, STRACCUM_TOOBIG);
25439  return 0;
25440  }else{
25441  p->nAlloc = (int)szNew;
25442  }
25443  if( p->db ){
25444  zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
25445  }else{
25446  zNew = sqlite3_realloc64(zOld, p->nAlloc);
25447  }
25448  if( zNew ){
25449  assert( p->zText!=0 || p->nChar==0 );
25450  if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
25451  p->zText = zNew;
25452  p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
25453  p->printfFlags |= SQLITE_PRINTF_MALLOCED;
25454  }else{
25455  sqlite3StrAccumReset(p);
25456  setStrAccumError(p, STRACCUM_NOMEM);
25457  return 0;
25458  }
25459  }
25460  return N;
25461 }
25462 
25463 /*
25464 ** Append N copies of character c to the given string buffer.
25465 */
25466 SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){
25467  testcase( p->nChar + (i64)N > 0x7fffffff );
25468  if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
25469  return;
25470  }
25471  assert( (p->zText==p->zBase)==!isMalloced(p) );
25472  while( (N--)>0 ) p->zText[p->nChar++] = c;
25473 }
25474 
25475 /*
25476 ** The StrAccum "p" is not large enough to accept N new bytes of z[].
25477 ** So enlarge if first, then do the append.
25478 **
25479 ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
25480 ** work (enlarging the buffer) using tail recursion, so that the
25481 ** sqlite3StrAccumAppend() routine can use fast calling semantics.
25482 */
25483 static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
25484  N = sqlite3StrAccumEnlarge(p, N);
25485  if( N>0 ){
25486  memcpy(&p->zText[p->nChar], z, N);
25487  p->nChar += N;
25488  }
25489  assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
25490 }
25491 
25492 /*
25493 ** Append N bytes of text from z to the StrAccum object. Increase the
25494 ** size of the memory allocation for StrAccum if necessary.
25495 */
25496 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
25497  assert( z!=0 || N==0 );
25498  assert( p->zText!=0 || p->nChar==0 || p->accError );
25499  assert( N>=0 );
25500  assert( p->accError==0 || p->nAlloc==0 );
25501  if( p->nChar+N >= p->nAlloc ){
25502  enlargeAndAppend(p,z,N);
25503  }else{
25504  assert( p->zText );
25505  p->nChar += N;
25506  memcpy(&p->zText[p->nChar-N], z, N);
25507  }
25508 }
25509 
25510 /*
25511 ** Append the complete text of zero-terminated string z[] to the p string.
25512 */
25513 SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
25514  sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
25515 }
25516 
25517 
25518 /*
25519 ** Finish off a string by making sure it is zero-terminated.
25520 ** Return a pointer to the resulting string. Return a NULL
25521 ** pointer if any kind of error was encountered.
25522 */
25523 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
25524  if( p->zText ){
25525  assert( (p->zText==p->zBase)==!isMalloced(p) );
25526  p->zText[p->nChar] = 0;
25527  if( p->mxAlloc>0 && !isMalloced(p) ){
25528  p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
25529  if( p->zText ){
25530  memcpy(p->zText, p->zBase, p->nChar+1);
25531  p->printfFlags |= SQLITE_PRINTF_MALLOCED;
25532  }else{
25533  setStrAccumError(p, STRACCUM_NOMEM);
25534  }
25535  }
25536  }
25537  return p->zText;
25538 }
25539 
25540 /*
25541 ** Reset an StrAccum string. Reclaim all malloced memory.
25542 */
25543 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
25544  assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
25545  if( isMalloced(p) ){
25546  sqlite3DbFree(p->db, p->zText);
25547  p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
25548  }
25549  p->zText = 0;
25550 }
25551 
25552 /*
25553 ** Initialize a string accumulator.
25554 **
25555 ** p: The accumulator to be initialized.
25556 ** db: Pointer to a database connection. May be NULL. Lookaside
25557 ** memory is used if not NULL. db->mallocFailed is set appropriately
25558 ** when not NULL.
25559 ** zBase: An initial buffer. May be NULL in which case the initial buffer
25560 ** is malloced.
25561 ** n: Size of zBase in bytes. If total space requirements never exceed
25562 ** n then no memory allocations ever occur.
25563 ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory
25564 ** allocations will ever occur.
25565 */
25566 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
25567  p->zText = p->zBase = zBase;
25568  p->db = db;
25569  p->nChar = 0;
25570  p->nAlloc = n;
25571  p->mxAlloc = mx;
25572  p->accError = 0;
25573  p->printfFlags = 0;
25574 }
25575 
25576 /*
25577 ** Print into memory obtained from sqliteMalloc(). Use the internal
25578 ** %-conversion extensions.
25579 */
25580 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
25581  char *z;
25582  char zBase[SQLITE_PRINT_BUF_SIZE];
25583  StrAccum acc;
25584  assert( db!=0 );
25585  sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
25586  db->aLimit[SQLITE_LIMIT_LENGTH]);
25587  acc.printfFlags = SQLITE_PRINTF_INTERNAL;
25588  sqlite3VXPrintf(&acc, zFormat, ap);
25589  z = sqlite3StrAccumFinish(&acc);
25590  if( acc.accError==STRACCUM_NOMEM ){
25591  sqlite3OomFault(db);
25592  }
25593  return z;
25594 }
25595 
25596 /*
25597 ** Print into memory obtained from sqliteMalloc(). Use the internal
25598 ** %-conversion extensions.
25599 */
25600 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
25601  va_list ap;
25602  char *z;
25603  va_start(ap, zFormat);
25604  z = sqlite3VMPrintf(db, zFormat, ap);
25605  va_end(ap);
25606  return z;
25607 }
25608 
25609 /*
25610 ** Print into memory obtained from sqlite3_malloc(). Omit the internal
25611 ** %-conversion extensions.
25612 */
25613 SQLITE_API char *SQLITE_STDCALL sqlite3_vmprintf(const char *zFormat, va_list ap){
25614  char *z;
25615  char zBase[SQLITE_PRINT_BUF_SIZE];
25616  StrAccum acc;
25617 
25618 #ifdef SQLITE_ENABLE_API_ARMOR
25619  if( zFormat==0 ){
25620  (void)SQLITE_MISUSE_BKPT;
25621  return 0;
25622  }
25623 #endif
25624 #ifndef SQLITE_OMIT_AUTOINIT
25625  if( sqlite3_initialize() ) return 0;
25626 #endif
25627  sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
25628  sqlite3VXPrintf(&acc, zFormat, ap);
25629  z = sqlite3StrAccumFinish(&acc);
25630  return z;
25631 }
25632 
25633 /*
25634 ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
25635 ** %-conversion extensions.
25636 */
25637 SQLITE_API char *SQLITE_CDECL sqlite3_mprintf(const char *zFormat, ...){
25638  va_list ap;
25639  char *z;
25640 #ifndef SQLITE_OMIT_AUTOINIT
25641  if( sqlite3_initialize() ) return 0;
25642 #endif
25643  va_start(ap, zFormat);
25644  z = sqlite3_vmprintf(zFormat, ap);
25645  va_end(ap);
25646  return z;
25647 }
25648 
25649 /*
25650 ** sqlite3_snprintf() works like snprintf() except that it ignores the
25651 ** current locale settings. This is important for SQLite because we
25652 ** are not able to use a "," as the decimal point in place of "." as
25653 ** specified by some locales.
25654 **
25655 ** Oops: The first two arguments of sqlite3_snprintf() are backwards
25656 ** from the snprintf() standard. Unfortunately, it is too late to change
25657 ** this without breaking compatibility, so we just have to live with the
25658 ** mistake.
25659 **
25660 ** sqlite3_vsnprintf() is the varargs version.
25661 */
25662 SQLITE_API char *SQLITE_STDCALL sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
25663  StrAccum acc;
25664  if( n<=0 ) return zBuf;
25665 #ifdef SQLITE_ENABLE_API_ARMOR
25666  if( zBuf==0 || zFormat==0 ) {
25667  (void)SQLITE_MISUSE_BKPT;
25668  if( zBuf ) zBuf[0] = 0;
25669  return zBuf;
25670  }
25671 #endif
25672  sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
25673  sqlite3VXPrintf(&acc, zFormat, ap);
25674  return sqlite3StrAccumFinish(&acc);
25675 }
25676 SQLITE_API char *SQLITE_CDECL sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
25677  char *z;
25678  va_list ap;
25679  va_start(ap,zFormat);
25680  z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
25681  va_end(ap);
25682  return z;
25683 }
25684 
25685 /*
25686 ** This is the routine that actually formats the sqlite3_log() message.
25687 ** We house it in a separate routine from sqlite3_log() to avoid using
25688 ** stack space on small-stack systems when logging is disabled.
25689 **
25690 ** sqlite3_log() must render into a static buffer. It cannot dynamically
25691 ** allocate memory because it might be called while the memory allocator
25692 ** mutex is held.
25693 **
25694 ** sqlite3VXPrintf() might ask for *temporary* memory allocations for
25695 ** certain format characters (%q) or for very large precisions or widths.
25696 ** Care must be taken that any sqlite3_log() calls that occur while the
25697 ** memory mutex is held do not use these mechanisms.
25698 */
25699 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
25700  StrAccum acc; /* String accumulator */
25701  char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
25702 
25703  sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
25704  sqlite3VXPrintf(&acc, zFormat, ap);
25705  sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
25706  sqlite3StrAccumFinish(&acc));
25707 }
25708 
25709 /*
25710 ** Format and write a message to the log if logging is enabled.
25711 */
25712 SQLITE_API void SQLITE_CDECL sqlite3_log(int iErrCode, const char *zFormat, ...){
25713  va_list ap; /* Vararg list */
25714  if( sqlite3GlobalConfig.xLog ){
25715  va_start(ap, zFormat);
25716  renderLogMsg(iErrCode, zFormat, ap);
25717  va_end(ap);
25718  }
25719 }
25720 
25721 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
25722 /*
25723 ** A version of printf() that understands %lld. Used for debugging.
25724 ** The printf() built into some versions of windows does not understand %lld
25725 ** and segfaults if you give it a long long int.
25726 */
25727 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
25728  va_list ap;
25729  StrAccum acc;
25730  char zBuf[500];
25731  sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
25732  va_start(ap,zFormat);
25733  sqlite3VXPrintf(&acc, zFormat, ap);
25734  va_end(ap);
25735  sqlite3StrAccumFinish(&acc);
25736  fprintf(stdout,"%s", zBuf);
25737  fflush(stdout);
25738 }
25739 #endif
25740 
25741 
25742 /*
25743 ** variable-argument wrapper around sqlite3VXPrintf(). The bFlags argument
25744 ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
25745 */
25746 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
25747  va_list ap;
25748  va_start(ap,zFormat);
25749  sqlite3VXPrintf(p, zFormat, ap);
25750  va_end(ap);
25751 }
25752 
25753 /************** End of printf.c **********************************************/
25754 /************** Begin file treeview.c ****************************************/
25755 /*
25756 ** 2015-06-08
25757 **
25758 ** The author disclaims copyright to this source code. In place of
25759 ** a legal notice, here is a blessing:
25760 **
25761 ** May you do good and not evil.
25762 ** May you find forgiveness for yourself and forgive others.
25763 ** May you share freely, never taking more than you give.
25764 **
25765 *************************************************************************
25766 **
25767 ** This file contains C code to implement the TreeView debugging routines.
25768 ** These routines print a parse tree to standard output for debugging and
25769 ** analysis.
25770 **
25771 ** The interfaces in this file is only available when compiling
25772 ** with SQLITE_DEBUG.
25773 */
25774 /* #include "sqliteInt.h" */
25775 #ifdef SQLITE_DEBUG
25776 
25777 /*
25778 ** Add a new subitem to the tree. The moreToFollow flag indicates that this
25779 ** is not the last item in the tree.
25780 */
25781 static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
25782  if( p==0 ){
25783  p = sqlite3_malloc64( sizeof(*p) );
25784  if( p==0 ) return 0;
25785  memset(p, 0, sizeof(*p));
25786  }else{
25787  p->iLevel++;
25788  }
25789  assert( moreToFollow==0 || moreToFollow==1 );
25790  if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
25791  return p;
25792 }
25793 
25794 /*
25795 ** Finished with one layer of the tree
25796 */
25797 static void sqlite3TreeViewPop(TreeView *p){
25798  if( p==0 ) return;
25799  p->iLevel--;
25800  if( p->iLevel<0 ) sqlite3_free(p);
25801 }
25802 
25803 /*
25804 ** Generate a single line of output for the tree, with a prefix that contains
25805 ** all the appropriate tree lines
25806 */
25807 static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
25808  va_list ap;
25809  int i;
25810  StrAccum acc;
25811  char zBuf[500];
25812  sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
25813  if( p ){
25814  for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
25815  sqlite3StrAccumAppend(&acc, p->bLine[i] ? "| " : " ", 4);
25816  }
25817  sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
25818  }
25819  va_start(ap, zFormat);
25820  sqlite3VXPrintf(&acc, zFormat, ap);
25821  va_end(ap);
25822  if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
25823  sqlite3StrAccumFinish(&acc);
25824  fprintf(stdout,"%s", zBuf);
25825  fflush(stdout);
25826 }
25827 
25828 /*
25829 ** Shorthand for starting a new tree item that consists of a single label
25830 */
25831 static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
25832  p = sqlite3TreeViewPush(p, moreFollows);
25833  sqlite3TreeViewLine(p, "%s", zLabel);
25834 }
25835 
25836 /*
25837 ** Generate a human-readable description of a WITH clause.
25838 */
25839 SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
25840  int i;
25841  if( pWith==0 ) return;
25842  if( pWith->nCte==0 ) return;
25843  if( pWith->pOuter ){
25844  sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
25845  }else{
25846  sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
25847  }
25848  if( pWith->nCte>0 ){
25849  pView = sqlite3TreeViewPush(pView, 1);
25850  for(i=0; i<pWith->nCte; i++){
25851  StrAccum x;
25852  char zLine[1000];
25853  const struct Cte *pCte = &pWith->a[i];
25854  sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
25855  sqlite3XPrintf(&x, "%s", pCte->zName);
25856  if( pCte->pCols && pCte->pCols->nExpr>0 ){
25857  char cSep = '(';
25858  int j;
25859  for(j=0; j<pCte->pCols->nExpr; j++){
25860  sqlite3XPrintf(&x, "%c%s", cSep, pCte->pCols->a[j].zName);
25861  cSep = ',';
25862  }
25863  sqlite3XPrintf(&x, ")");
25864  }
25865  sqlite3XPrintf(&x, " AS");
25866  sqlite3StrAccumFinish(&x);
25867  sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
25868  sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
25869  sqlite3TreeViewPop(pView);
25870  }
25871  sqlite3TreeViewPop(pView);
25872  }
25873 }
25874 
25875 
25876 /*
25877 ** Generate a human-readable description of a the Select object.
25878 */
25879 SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
25880  int n = 0;
25881  int cnt = 0;
25882  pView = sqlite3TreeViewPush(pView, moreToFollow);
25883  if( p->pWith ){
25884  sqlite3TreeViewWith(pView, p->pWith, 1);
25885  cnt = 1;
25886  sqlite3TreeViewPush(pView, 1);
25887  }
25888  do{
25889  sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x nSelectRow=%d",
25890  ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
25891  ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags,
25892  (int)p->nSelectRow
25893  );
25894  if( cnt++ ) sqlite3TreeViewPop(pView);
25895  if( p->pPrior ){
25896  n = 1000;
25897  }else{
25898  n = 0;
25899  if( p->pSrc && p->pSrc->nSrc ) n++;
25900  if( p->pWhere ) n++;
25901  if( p->pGroupBy ) n++;
25902  if( p->pHaving ) n++;
25903  if( p->pOrderBy ) n++;
25904  if( p->pLimit ) n++;
25905  if( p->pOffset ) n++;
25906  }
25907  sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
25908  if( p->pSrc && p->pSrc->nSrc ){
25909  int i;
25910  pView = sqlite3TreeViewPush(pView, (n--)>0);
25911  sqlite3TreeViewLine(pView, "FROM");
25912  for(i=0; i<p->pSrc->nSrc; i++){
25913  struct SrcList_item *pItem = &p->pSrc->a[i];
25914  StrAccum x;
25915  char zLine[100];
25916  sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
25917  sqlite3XPrintf(&x, "{%d,*}", pItem->iCursor);
25918  if( pItem->zDatabase ){
25919  sqlite3XPrintf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
25920  }else if( pItem->zName ){
25921  sqlite3XPrintf(&x, " %s", pItem->zName);
25922  }
25923  if( pItem->pTab ){
25924  sqlite3XPrintf(&x, " tabname=%Q", pItem->pTab->zName);
25925  }
25926  if( pItem->zAlias ){
25927  sqlite3XPrintf(&x, " (AS %s)", pItem->zAlias);
25928  }
25929  if( pItem->fg.jointype & JT_LEFT ){
25930  sqlite3XPrintf(&x, " LEFT-JOIN");
25931  }
25932  sqlite3StrAccumFinish(&x);
25933  sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
25934  if( pItem->pSelect ){
25935  sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
25936  }
25937  if( pItem->fg.isTabFunc ){
25938  sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
25939  }
25940  sqlite3TreeViewPop(pView);
25941  }
25942  sqlite3TreeViewPop(pView);
25943  }
25944  if( p->pWhere ){
25945  sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
25946  sqlite3TreeViewExpr(pView, p->pWhere, 0);
25947  sqlite3TreeViewPop(pView);
25948  }
25949  if( p->pGroupBy ){
25950  sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
25951  }
25952  if( p->pHaving ){
25953  sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
25954  sqlite3TreeViewExpr(pView, p->pHaving, 0);
25955  sqlite3TreeViewPop(pView);
25956  }
25957  if( p->pOrderBy ){
25958  sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
25959  }
25960  if( p->pLimit ){
25961  sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
25962  sqlite3TreeViewExpr(pView, p->pLimit, 0);
25963  sqlite3TreeViewPop(pView);
25964  }
25965  if( p->pOffset ){
25966  sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
25967  sqlite3TreeViewExpr(pView, p->pOffset, 0);
25968  sqlite3TreeViewPop(pView);
25969  }
25970  if( p->pPrior ){
25971  const char *zOp = "UNION";
25972  switch( p->op ){
25973  case TK_ALL: zOp = "UNION ALL"; break;
25974  case TK_INTERSECT: zOp = "INTERSECT"; break;
25975  case TK_EXCEPT: zOp = "EXCEPT"; break;
25976  }
25977  sqlite3TreeViewItem(pView, zOp, 1);
25978  }
25979  p = p->pPrior;
25980  }while( p!=0 );
25981  sqlite3TreeViewPop(pView);
25982 }
25983 
25984 /*
25985 ** Generate a human-readable explanation of an expression tree.
25986 */
25987 SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
25988  const char *zBinOp = 0; /* Binary operator */
25989  const char *zUniOp = 0; /* Unary operator */
25990  char zFlgs[30];
25991  pView = sqlite3TreeViewPush(pView, moreToFollow);
25992  if( pExpr==0 ){
25993  sqlite3TreeViewLine(pView, "nil");
25994  sqlite3TreeViewPop(pView);
25995  return;
25996  }
25997  if( pExpr->flags ){
25998  sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x",pExpr->flags);
25999  }else{
26000  zFlgs[0] = 0;
26001  }
26002  switch( pExpr->op ){
26003  case TK_AGG_COLUMN: {
26004  sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
26005  pExpr->iTable, pExpr->iColumn, zFlgs);
26006  break;
26007  }
26008  case TK_COLUMN: {
26009  if( pExpr->iTable<0 ){
26010  /* This only happens when coding check constraints */
26011  sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
26012  }else{
26013  sqlite3TreeViewLine(pView, "{%d:%d}%s",
26014  pExpr->iTable, pExpr->iColumn, zFlgs);
26015  }
26016  break;
26017  }
26018  case TK_INTEGER: {
26019  if( pExpr->flags & EP_IntValue ){
26020  sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
26021  }else{
26022  sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
26023  }
26024  break;
26025  }
26026 #ifndef SQLITE_OMIT_FLOATING_POINT
26027  case TK_FLOAT: {
26028  sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
26029  break;
26030  }
26031 #endif
26032  case TK_STRING: {
26033  sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
26034  break;
26035  }
26036  case TK_NULL: {
26037  sqlite3TreeViewLine(pView,"NULL");
26038  break;
26039  }
26040 #ifndef SQLITE_OMIT_BLOB_LITERAL
26041  case TK_BLOB: {
26042  sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
26043  break;
26044  }
26045 #endif
26046  case TK_VARIABLE: {
26047  sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
26048  pExpr->u.zToken, pExpr->iColumn);
26049  break;
26050  }
26051  case TK_REGISTER: {
26052  sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
26053  break;
26054  }
26055  case TK_ID: {
26056  sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
26057  break;
26058  }
26059 #ifndef SQLITE_OMIT_CAST
26060  case TK_CAST: {
26061  /* Expressions of the form: CAST(pLeft AS token) */
26062  sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
26063  sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
26064  break;
26065  }
26066 #endif /* SQLITE_OMIT_CAST */
26067  case TK_LT: zBinOp = "LT"; break;
26068  case TK_LE: zBinOp = "LE"; break;
26069  case TK_GT: zBinOp = "GT"; break;
26070  case TK_GE: zBinOp = "GE"; break;
26071  case TK_NE: zBinOp = "NE"; break;
26072  case TK_EQ: zBinOp = "EQ"; break;
26073  case TK_IS: zBinOp = "IS"; break;
26074  case TK_ISNOT: zBinOp = "ISNOT"; break;
26075  case TK_AND: zBinOp = "AND"; break;
26076  case TK_OR: zBinOp = "OR"; break;
26077  case TK_PLUS: zBinOp = "ADD"; break;
26078  case TK_STAR: zBinOp = "MUL"; break;
26079  case TK_MINUS: zBinOp = "SUB"; break;
26080  case TK_REM: zBinOp = "REM"; break;
26081  case TK_BITAND: zBinOp = "BITAND"; break;
26082  case TK_BITOR: zBinOp = "BITOR"; break;
26083  case TK_SLASH: zBinOp = "DIV"; break;
26084  case TK_LSHIFT: zBinOp = "LSHIFT"; break;
26085  case TK_RSHIFT: zBinOp = "RSHIFT"; break;
26086  case TK_CONCAT: zBinOp = "CONCAT"; break;
26087  case TK_DOT: zBinOp = "DOT"; break;
26088 
26089  case TK_UMINUS: zUniOp = "UMINUS"; break;
26090  case TK_UPLUS: zUniOp = "UPLUS"; break;
26091  case TK_BITNOT: zUniOp = "BITNOT"; break;
26092  case TK_NOT: zUniOp = "NOT"; break;
26093  case TK_ISNULL: zUniOp = "ISNULL"; break;
26094  case TK_NOTNULL: zUniOp = "NOTNULL"; break;
26095 
26096  case TK_SPAN: {
26097  sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
26098  sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
26099  break;
26100  }
26101 
26102  case TK_COLLATE: {
26103  sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
26104  sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
26105  break;
26106  }
26107 
26108  case TK_AGG_FUNCTION:
26109  case TK_FUNCTION: {
26110  ExprList *pFarg; /* List of function arguments */
26111  if( ExprHasProperty(pExpr, EP_TokenOnly) ){
26112  pFarg = 0;
26113  }else{
26114  pFarg = pExpr->x.pList;
26115  }
26116  if( pExpr->op==TK_AGG_FUNCTION ){
26117  sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
26118  pExpr->op2, pExpr->u.zToken);
26119  }else{
26120  sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
26121  }
26122  if( pFarg ){
26123  sqlite3TreeViewExprList(pView, pFarg, 0, 0);
26124  }
26125  break;
26126  }
26127 #ifndef SQLITE_OMIT_SUBQUERY
26128  case TK_EXISTS: {
26129  sqlite3TreeViewLine(pView, "EXISTS-expr");
26130  sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
26131  break;
26132  }
26133  case TK_SELECT: {
26134  sqlite3TreeViewLine(pView, "SELECT-expr");
26135  sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
26136  break;
26137  }
26138  case TK_IN: {
26139  sqlite3TreeViewLine(pView, "IN");
26140  sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
26141  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
26142  sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
26143  }else{
26144  sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
26145  }
26146  break;
26147  }
26148 #endif /* SQLITE_OMIT_SUBQUERY */
26149 
26150  /*
26151  ** x BETWEEN y AND z
26152  **
26153  ** This is equivalent to
26154  **
26155  ** x>=y AND x<=z
26156  **
26157  ** X is stored in pExpr->pLeft.
26158  ** Y is stored in pExpr->pList->a[0].pExpr.
26159  ** Z is stored in pExpr->pList->a[1].pExpr.
26160  */
26161  case TK_BETWEEN: {
26162  Expr *pX = pExpr->pLeft;
26163  Expr *pY = pExpr->x.pList->a[0].pExpr;
26164  Expr *pZ = pExpr->x.pList->a[1].pExpr;
26165  sqlite3TreeViewLine(pView, "BETWEEN");
26166  sqlite3TreeViewExpr(pView, pX, 1);
26167  sqlite3TreeViewExpr(pView, pY, 1);
26168  sqlite3TreeViewExpr(pView, pZ, 0);
26169  break;
26170  }
26171  case TK_TRIGGER: {
26172  /* If the opcode is TK_TRIGGER, then the expression is a reference
26173  ** to a column in the new.* or old.* pseudo-tables available to
26174  ** trigger programs. In this case Expr.iTable is set to 1 for the
26175  ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
26176  ** is set to the column of the pseudo-table to read, or to -1 to
26177  ** read the rowid field.
26178  */
26179  sqlite3TreeViewLine(pView, "%s(%d)",
26180  pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
26181  break;
26182  }
26183  case TK_CASE: {
26184  sqlite3TreeViewLine(pView, "CASE");
26185  sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
26186  sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
26187  break;
26188  }
26189 #ifndef SQLITE_OMIT_TRIGGER
26190  case TK_RAISE: {
26191  const char *zType = "unk";
26192  switch( pExpr->affinity ){
26193  case OE_Rollback: zType = "rollback"; break;
26194  case OE_Abort: zType = "abort"; break;
26195  case OE_Fail: zType = "fail"; break;
26196  case OE_Ignore: zType = "ignore"; break;
26197  }
26198  sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
26199  break;
26200  }
26201 #endif
26202  case TK_MATCH: {
26203  sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s",
26204  pExpr->iTable, pExpr->iColumn, zFlgs);
26205  sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
26206  break;
26207  }
26208  default: {
26209  sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
26210  break;
26211  }
26212  }
26213  if( zBinOp ){
26214  sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
26215  sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
26216  sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
26217  }else if( zUniOp ){
26218  sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
26219  sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
26220  }
26221  sqlite3TreeViewPop(pView);
26222 }
26223 
26224 /*
26225 ** Generate a human-readable explanation of an expression list.
26226 */
26227 SQLITE_PRIVATE void sqlite3TreeViewExprList(
26228  TreeView *pView,
26229  const ExprList *pList,
26230  u8 moreToFollow,
26231  const char *zLabel
26232 ){
26233  int i;
26234  pView = sqlite3TreeViewPush(pView, moreToFollow);
26235  if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
26236  if( pList==0 ){
26237  sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
26238  }else{
26239  sqlite3TreeViewLine(pView, "%s", zLabel);
26240  for(i=0; i<pList->nExpr; i++){
26241  int j = pList->a[i].u.x.iOrderByCol;
26242  if( j ){
26243  sqlite3TreeViewPush(pView, 0);
26244  sqlite3TreeViewLine(pView, "iOrderByCol=%d", j);
26245  }
26246  sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
26247  if( j ) sqlite3TreeViewPop(pView);
26248  }
26249  }
26250  sqlite3TreeViewPop(pView);
26251 }
26252 
26253 #endif /* SQLITE_DEBUG */
26254 
26255 /************** End of treeview.c ********************************************/
26256 /************** Begin file random.c ******************************************/
26257 /*
26258 ** 2001 September 15
26259 **
26260 ** The author disclaims copyright to this source code. In place of
26261 ** a legal notice, here is a blessing:
26262 **
26263 ** May you do good and not evil.
26264 ** May you find forgiveness for yourself and forgive others.
26265 ** May you share freely, never taking more than you give.
26266 **
26267 *************************************************************************
26268 ** This file contains code to implement a pseudo-random number
26269 ** generator (PRNG) for SQLite.
26270 **
26271 ** Random numbers are used by some of the database backends in order
26272 ** to generate random integer keys for tables or random filenames.
26273 */
26274 /* #include "sqliteInt.h" */
26275 
26276 
26277 /* All threads share a single random number generator.
26278 ** This structure is the current state of the generator.
26279 */
26280 static SQLITE_WSD struct sqlite3PrngType {
26281  unsigned char isInit; /* True if initialized */
26282  unsigned char i, j; /* State variables */
26283  unsigned char s[256]; /* State variables */
26284 } sqlite3Prng;
26285 
26286 /*
26287 ** Return N random bytes.
26288 */
26289 SQLITE_API void SQLITE_STDCALL sqlite3_randomness(int N, void *pBuf){
26290  unsigned char t;
26291  unsigned char *zBuf = pBuf;
26292 
26293  /* The "wsdPrng" macro will resolve to the pseudo-random number generator
26294  ** state vector. If writable static data is unsupported on the target,
26295  ** we have to locate the state vector at run-time. In the more common
26296  ** case where writable static data is supported, wsdPrng can refer directly
26297  ** to the "sqlite3Prng" state vector declared above.
26298  */
26299 #ifdef SQLITE_OMIT_WSD
26300  struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
26301 # define wsdPrng p[0]
26302 #else
26303 # define wsdPrng sqlite3Prng
26304 #endif
26305 
26306 #if SQLITE_THREADSAFE
26307  sqlite3_mutex *mutex;
26308 #endif
26309 
26310 #ifndef SQLITE_OMIT_AUTOINIT
26311  if( sqlite3_initialize() ) return;
26312 #endif
26313 
26314 #if SQLITE_THREADSAFE
26315  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
26316 #endif
26317 
26318  sqlite3_mutex_enter(mutex);
26319  if( N<=0 || pBuf==0 ){
26320  wsdPrng.isInit = 0;
26321  sqlite3_mutex_leave(mutex);
26322  return;
26323  }
26324 
26325  /* Initialize the state of the random number generator once,
26326  ** the first time this routine is called. The seed value does
26327  ** not need to contain a lot of randomness since we are not
26328  ** trying to do secure encryption or anything like that...
26329  **
26330  ** Nothing in this file or anywhere else in SQLite does any kind of
26331  ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
26332  ** number generator) not as an encryption device.
26333  */
26334  if( !wsdPrng.isInit ){
26335  int i;
26336  char k[256];
26337  wsdPrng.j = 0;
26338  wsdPrng.i = 0;
26339  sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
26340  for(i=0; i<256; i++){
26341  wsdPrng.s[i] = (u8)i;
26342  }
26343  for(i=0; i<256; i++){
26344  wsdPrng.j += wsdPrng.s[i] + k[i];
26345  t = wsdPrng.s[wsdPrng.j];
26346  wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
26347  wsdPrng.s[i] = t;
26348  }
26349  wsdPrng.isInit = 1;
26350  }
26351 
26352  assert( N>0 );
26353  do{
26354  wsdPrng.i++;
26355  t = wsdPrng.s[wsdPrng.i];
26356  wsdPrng.j += t;
26357  wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
26358  wsdPrng.s[wsdPrng.j] = t;
26359  t += wsdPrng.s[wsdPrng.i];
26360  *(zBuf++) = wsdPrng.s[t];
26361  }while( --N );
26362  sqlite3_mutex_leave(mutex);
26363 }
26364 
26365 #ifndef SQLITE_OMIT_BUILTIN_TEST
26366 /*
26367 ** For testing purposes, we sometimes want to preserve the state of
26368 ** PRNG and restore the PRNG to its saved state at a later time, or
26369 ** to reset the PRNG to its initial state. These routines accomplish
26370 ** those tasks.
26371 **
26372 ** The sqlite3_test_control() interface calls these routines to
26373 ** control the PRNG.
26374 */
26375 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
26376 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
26377  memcpy(
26378  &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
26379  &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
26380  sizeof(sqlite3Prng)
26381  );
26382 }
26383 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
26384  memcpy(
26385  &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
26386  &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
26387  sizeof(sqlite3Prng)
26388  );
26389 }
26390 #endif /* SQLITE_OMIT_BUILTIN_TEST */
26391 
26392 /************** End of random.c **********************************************/
26393 /************** Begin file threads.c *****************************************/
26394 /*
26395 ** 2012 July 21
26396 **
26397 ** The author disclaims copyright to this source code. In place of
26398 ** a legal notice, here is a blessing:
26399 **
26400 ** May you do good and not evil.
26401 ** May you find forgiveness for yourself and forgive others.
26402 ** May you share freely, never taking more than you give.
26403 **
26404 ******************************************************************************
26405 **
26406 ** This file presents a simple cross-platform threading interface for
26407 ** use internally by SQLite.
26408 **
26409 ** A "thread" can be created using sqlite3ThreadCreate(). This thread
26410 ** runs independently of its creator until it is joined using
26411 ** sqlite3ThreadJoin(), at which point it terminates.
26412 **
26413 ** Threads do not have to be real. It could be that the work of the
26414 ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
26415 ** or sqlite3ThreadJoin() call. This is, in fact, what happens in
26416 ** single threaded systems. Nothing in SQLite requires multiple threads.
26417 ** This interface exists so that applications that want to take advantage
26418 ** of multiple cores can do so, while also allowing applications to stay
26419 ** single-threaded if desired.
26420 */
26421 /* #include "sqliteInt.h" */
26422 #if SQLITE_OS_WIN
26423 /* # include "os_win.h" */
26424 #endif
26425 
26426 #if SQLITE_MAX_WORKER_THREADS>0
26427 
26428 /********************************* Unix Pthreads ****************************/
26429 #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
26430 
26431 #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
26432 /* #include <pthread.h> */
26433 
26434 /* A running thread */
26435 struct SQLiteThread {
26436  pthread_t tid; /* Thread ID */
26437  int done; /* Set to true when thread finishes */
26438  void *pOut; /* Result returned by the thread */
26439  void *(*xTask)(void*); /* The thread routine */
26440  void *pIn; /* Argument to the thread */
26441 };
26442 
26443 /* Create a new thread */
26444 SQLITE_PRIVATE int sqlite3ThreadCreate(
26445  SQLiteThread **ppThread, /* OUT: Write the thread object here */
26446  void *(*xTask)(void*), /* Routine to run in a separate thread */
26447  void *pIn /* Argument passed into xTask() */
26448 ){
26449  SQLiteThread *p;
26450  int rc;
26451 
26452  assert( ppThread!=0 );
26453  assert( xTask!=0 );
26454  /* This routine is never used in single-threaded mode */
26455  assert( sqlite3GlobalConfig.bCoreMutex!=0 );
26456 
26457  *ppThread = 0;
26458  p = sqlite3Malloc(sizeof(*p));
26459  if( p==0 ) return SQLITE_NOMEM_BKPT;
26460  memset(p, 0, sizeof(*p));
26461  p->xTask = xTask;
26462  p->pIn = pIn;
26463  /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
26464  ** function that returns SQLITE_ERROR when passed the argument 200, that
26465  ** forces worker threads to run sequentially and deterministically
26466  ** for testing purposes. */
26467  if( sqlite3FaultSim(200) ){
26468  rc = 1;
26469  }else{
26470  rc = pthread_create(&p->tid, 0, xTask, pIn);
26471  }
26472  if( rc ){
26473  p->done = 1;
26474  p->pOut = xTask(pIn);
26475  }
26476  *ppThread = p;
26477  return SQLITE_OK;
26478 }
26479 
26480 /* Get the results of the thread */
26481 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
26482  int rc;
26483 
26484  assert( ppOut!=0 );
26485  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
26486  if( p->done ){
26487  *ppOut = p->pOut;
26488  rc = SQLITE_OK;
26489  }else{
26490  rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
26491  }
26492  sqlite3_free(p);
26493  return rc;
26494 }
26495 
26496 #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
26497 /******************************** End Unix Pthreads *************************/
26498 
26499 
26500 /********************************* Win32 Threads ****************************/
26501 #if SQLITE_OS_WIN_THREADS
26502 
26503 #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
26504 #include <process.h>
26505 
26506 /* A running thread */
26507 struct SQLiteThread {
26508  void *tid; /* The thread handle */
26509  unsigned id; /* The thread identifier */
26510  void *(*xTask)(void*); /* The routine to run as a thread */
26511  void *pIn; /* Argument to xTask */
26512  void *pResult; /* Result of xTask */
26513 };
26514 
26515 /* Thread procedure Win32 compatibility shim */
26516 static unsigned __stdcall sqlite3ThreadProc(
26517  void *pArg /* IN: Pointer to the SQLiteThread structure */
26518 ){
26519  SQLiteThread *p = (SQLiteThread *)pArg;
26520 
26521  assert( p!=0 );
26522 #if 0
26523  /*
26524  ** This assert appears to trigger spuriously on certain
26525  ** versions of Windows, possibly due to _beginthreadex()
26526  ** and/or CreateThread() not fully setting their thread
26527  ** ID parameter before starting the thread.
26528  */
26529  assert( p->id==GetCurrentThreadId() );
26530 #endif
26531  assert( p->xTask!=0 );
26532  p->pResult = p->xTask(p->pIn);
26533 
26534  _endthreadex(0);
26535  return 0; /* NOT REACHED */
26536 }
26537 
26538 /* Create a new thread */
26539 SQLITE_PRIVATE int sqlite3ThreadCreate(
26540  SQLiteThread **ppThread, /* OUT: Write the thread object here */
26541  void *(*xTask)(void*), /* Routine to run in a separate thread */
26542  void *pIn /* Argument passed into xTask() */
26543 ){
26544  SQLiteThread *p;
26545 
26546  assert( ppThread!=0 );
26547  assert( xTask!=0 );
26548  *ppThread = 0;
26549  p = sqlite3Malloc(sizeof(*p));
26550  if( p==0 ) return SQLITE_NOMEM_BKPT;
26551  /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
26552  ** function that returns SQLITE_ERROR when passed the argument 200, that
26553  ** forces worker threads to run sequentially and deterministically
26554  ** (via the sqlite3FaultSim() term of the conditional) for testing
26555  ** purposes. */
26556  if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
26557  memset(p, 0, sizeof(*p));
26558  }else{
26559  p->xTask = xTask;
26560  p->pIn = pIn;
26561  p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
26562  if( p->tid==0 ){
26563  memset(p, 0, sizeof(*p));
26564  }
26565  }
26566  if( p->xTask==0 ){
26567  p->id = GetCurrentThreadId();
26568  p->pResult = xTask(pIn);
26569  }
26570  *ppThread = p;
26571  return SQLITE_OK;
26572 }
26573 
26574 SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
26575 
26576 /* Get the results of the thread */
26577 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
26578  DWORD rc;
26579  BOOL bRc;
26580 
26581  assert( ppOut!=0 );
26582  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
26583  if( p->xTask==0 ){
26584  /* assert( p->id==GetCurrentThreadId() ); */
26585  rc = WAIT_OBJECT_0;
26586  assert( p->tid==0 );
26587  }else{
26588  assert( p->id!=0 && p->id!=GetCurrentThreadId() );
26589  rc = sqlite3Win32Wait((HANDLE)p->tid);
26590  assert( rc!=WAIT_IO_COMPLETION );
26591  bRc = CloseHandle((HANDLE)p->tid);
26592  assert( bRc );
26593  }
26594  if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
26595  sqlite3_free(p);
26596  return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
26597 }
26598 
26599 #endif /* SQLITE_OS_WIN_THREADS */
26600 /******************************** End Win32 Threads *************************/
26601 
26602 
26603 /********************************* Single-Threaded **************************/
26604 #ifndef SQLITE_THREADS_IMPLEMENTED
26605 /*
26606 ** This implementation does not actually create a new thread. It does the
26607 ** work of the thread in the main thread, when either the thread is created
26608 ** or when it is joined
26609 */
26610 
26611 /* A running thread */
26612 struct SQLiteThread {
26613  void *(*xTask)(void*); /* The routine to run as a thread */
26614  void *pIn; /* Argument to xTask */
26615  void *pResult; /* Result of xTask */
26616 };
26617 
26618 /* Create a new thread */
26619 SQLITE_PRIVATE int sqlite3ThreadCreate(
26620  SQLiteThread **ppThread, /* OUT: Write the thread object here */
26621  void *(*xTask)(void*), /* Routine to run in a separate thread */
26622  void *pIn /* Argument passed into xTask() */
26623 ){
26624  SQLiteThread *p;
26625 
26626  assert( ppThread!=0 );
26627  assert( xTask!=0 );
26628  *ppThread = 0;
26629  p = sqlite3Malloc(sizeof(*p));
26630  if( p==0 ) return SQLITE_NOMEM_BKPT;
26631  if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
26632  p->xTask = xTask;
26633  p->pIn = pIn;
26634  }else{
26635  p->xTask = 0;
26636  p->pResult = xTask(pIn);
26637  }
26638  *ppThread = p;
26639  return SQLITE_OK;
26640 }
26641 
26642 /* Get the results of the thread */
26643 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
26644 
26645  assert( ppOut!=0 );
26646  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
26647  if( p->xTask ){
26648  *ppOut = p->xTask(p->pIn);
26649  }else{
26650  *ppOut = p->pResult;
26651  }
26652  sqlite3_free(p);
26653 
26654 #if defined(SQLITE_TEST)
26655  {
26656  void *pTstAlloc = sqlite3Malloc(10);
26657  if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
26658  sqlite3_free(pTstAlloc);
26659  }
26660 #endif
26661 
26662  return SQLITE_OK;
26663 }
26664 
26665 #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
26666 /****************************** End Single-Threaded *************************/
26667 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
26668 
26669 /************** End of threads.c *********************************************/
26670 /************** Begin file utf.c *********************************************/
26671 /*
26672 ** 2004 April 13
26673 **
26674 ** The author disclaims copyright to this source code. In place of
26675 ** a legal notice, here is a blessing:
26676 **
26677 ** May you do good and not evil.
26678 ** May you find forgiveness for yourself and forgive others.
26679 ** May you share freely, never taking more than you give.
26680 **
26681 *************************************************************************
26682 ** This file contains routines used to translate between UTF-8,
26683 ** UTF-16, UTF-16BE, and UTF-16LE.
26684 **
26685 ** Notes on UTF-8:
26686 **
26687 ** Byte-0 Byte-1 Byte-2 Byte-3 Value
26688 ** 0xxxxxxx 00000000 00000000 0xxxxxxx
26689 ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
26690 ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
26691 ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
26692 **
26693 **
26694 ** Notes on UTF-16: (with wwww+1==uuuuu)
26695 **
26696 ** Word-0 Word-1 Value
26697 ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
26698 ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
26699 **
26700 **
26701 ** BOM or Byte Order Mark:
26702 ** 0xff 0xfe little-endian utf-16 follows
26703 ** 0xfe 0xff big-endian utf-16 follows
26704 **
26705 */
26706 /* #include "sqliteInt.h" */
26707 /* #include <assert.h> */
26708 /* #include "vdbeInt.h" */
26709 
26710 #if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
26711 /*
26712 ** The following constant value is used by the SQLITE_BIGENDIAN and
26713 ** SQLITE_LITTLEENDIAN macros.
26714 */
26715 SQLITE_PRIVATE const int sqlite3one = 1;
26716 #endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
26717 
26718 /*
26719 ** This lookup table is used to help decode the first byte of
26720 ** a multi-byte UTF8 character.
26721 */
26722 static const unsigned char sqlite3Utf8Trans1[] = {
26723  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
26724  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
26725  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
26726  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
26727  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
26728  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
26729  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
26730  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
26731 };
26732 
26733 
26734 #define WRITE_UTF8(zOut, c) { \
26735  if( c<0x00080 ){ \
26736  *zOut++ = (u8)(c&0xFF); \
26737  } \
26738  else if( c<0x00800 ){ \
26739  *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
26740  *zOut++ = 0x80 + (u8)(c & 0x3F); \
26741  } \
26742  else if( c<0x10000 ){ \
26743  *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
26744  *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
26745  *zOut++ = 0x80 + (u8)(c & 0x3F); \
26746  }else{ \
26747  *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
26748  *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
26749  *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
26750  *zOut++ = 0x80 + (u8)(c & 0x3F); \
26751  } \
26752 }
26753 
26754 #define WRITE_UTF16LE(zOut, c) { \
26755  if( c<=0xFFFF ){ \
26756  *zOut++ = (u8)(c&0x00FF); \
26757  *zOut++ = (u8)((c>>8)&0x00FF); \
26758  }else{ \
26759  *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
26760  *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
26761  *zOut++ = (u8)(c&0x00FF); \
26762  *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
26763  } \
26764 }
26765 
26766 #define WRITE_UTF16BE(zOut, c) { \
26767  if( c<=0xFFFF ){ \
26768  *zOut++ = (u8)((c>>8)&0x00FF); \
26769  *zOut++ = (u8)(c&0x00FF); \
26770  }else{ \
26771  *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
26772  *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
26773  *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
26774  *zOut++ = (u8)(c&0x00FF); \
26775  } \
26776 }
26777 
26778 #define READ_UTF16LE(zIn, TERM, c){ \
26779  c = (*zIn++); \
26780  c += ((*zIn++)<<8); \
26781  if( c>=0xD800 && c<0xE000 && TERM ){ \
26782  int c2 = (*zIn++); \
26783  c2 += ((*zIn++)<<8); \
26784  c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
26785  } \
26786 }
26787 
26788 #define READ_UTF16BE(zIn, TERM, c){ \
26789  c = ((*zIn++)<<8); \
26790  c += (*zIn++); \
26791  if( c>=0xD800 && c<0xE000 && TERM ){ \
26792  int c2 = ((*zIn++)<<8); \
26793  c2 += (*zIn++); \
26794  c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
26795  } \
26796 }
26797 
26798 /*
26799 ** Translate a single UTF-8 character. Return the unicode value.
26800 **
26801 ** During translation, assume that the byte that zTerm points
26802 ** is a 0x00.
26803 **
26804 ** Write a pointer to the next unread byte back into *pzNext.
26805 **
26806 ** Notes On Invalid UTF-8:
26807 **
26808 ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
26809 ** be encoded as a multi-byte character. Any multi-byte character that
26810 ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
26811 **
26812 ** * This routine never allows a UTF16 surrogate value to be encoded.
26813 ** If a multi-byte character attempts to encode a value between
26814 ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
26815 **
26816 ** * Bytes in the range of 0x80 through 0xbf which occur as the first
26817 ** byte of a character are interpreted as single-byte characters
26818 ** and rendered as themselves even though they are technically
26819 ** invalid characters.
26820 **
26821 ** * This routine accepts over-length UTF8 encodings
26822 ** for unicode values 0x80 and greater. It does not change over-length
26823 ** encodings to 0xfffd as some systems recommend.
26824 */
26825 #define READ_UTF8(zIn, zTerm, c) \
26826  c = *(zIn++); \
26827  if( c>=0xc0 ){ \
26828  c = sqlite3Utf8Trans1[c-0xc0]; \
26829  while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
26830  c = (c<<6) + (0x3f & *(zIn++)); \
26831  } \
26832  if( c<0x80 \
26833  || (c&0xFFFFF800)==0xD800 \
26834  || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
26835  }
26836 SQLITE_PRIVATE u32 sqlite3Utf8Read(
26837  const unsigned char **pz /* Pointer to string from which to read char */
26838 ){
26839  unsigned int c;
26840 
26841  /* Same as READ_UTF8() above but without the zTerm parameter.
26842  ** For this routine, we assume the UTF8 string is always zero-terminated.
26843  */
26844  c = *((*pz)++);
26845  if( c>=0xc0 ){
26846  c = sqlite3Utf8Trans1[c-0xc0];
26847  while( (*(*pz) & 0xc0)==0x80 ){
26848  c = (c<<6) + (0x3f & *((*pz)++));
26849  }
26850  if( c<0x80
26851  || (c&0xFFFFF800)==0xD800
26852  || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
26853  }
26854  return c;
26855 }
26856 
26857 
26858 
26859 
26860 /*
26861 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
26862 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
26863 */
26864 /* #define TRANSLATE_TRACE 1 */
26865 
26866 #ifndef SQLITE_OMIT_UTF16
26867 /*
26868 ** This routine transforms the internal text encoding used by pMem to
26869 ** desiredEnc. It is an error if the string is already of the desired
26870 ** encoding, or if *pMem does not contain a string value.
26871 */
26872 SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
26873  int len; /* Maximum length of output string in bytes */
26874  unsigned char *zOut; /* Output buffer */
26875  unsigned char *zIn; /* Input iterator */
26876  unsigned char *zTerm; /* End of input */
26877  unsigned char *z; /* Output iterator */
26878  unsigned int c;
26879 
26880  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
26881  assert( pMem->flags&MEM_Str );
26882  assert( pMem->enc!=desiredEnc );
26883  assert( pMem->enc!=0 );
26884  assert( pMem->n>=0 );
26885 
26886 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
26887  {
26888  char zBuf[100];
26889  sqlite3VdbeMemPrettyPrint(pMem, zBuf);
26890  fprintf(stderr, "INPUT: %s\n", zBuf);
26891  }
26892 #endif
26893 
26894  /* If the translation is between UTF-16 little and big endian, then
26895  ** all that is required is to swap the byte order. This case is handled
26896  ** differently from the others.
26897  */
26898  if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
26899  u8 temp;
26900  int rc;
26901  rc = sqlite3VdbeMemMakeWriteable(pMem);
26902  if( rc!=SQLITE_OK ){
26903  assert( rc==SQLITE_NOMEM );
26904  return SQLITE_NOMEM_BKPT;
26905  }
26906  zIn = (u8*)pMem->z;
26907  zTerm = &zIn[pMem->n&~1];
26908  while( zIn<zTerm ){
26909  temp = *zIn;
26910  *zIn = *(zIn+1);
26911  zIn++;
26912  *zIn++ = temp;
26913  }
26914  pMem->enc = desiredEnc;
26915  goto translate_out;
26916  }
26917 
26918  /* Set len to the maximum number of bytes required in the output buffer. */
26919  if( desiredEnc==SQLITE_UTF8 ){
26920  /* When converting from UTF-16, the maximum growth results from
26921  ** translating a 2-byte character to a 4-byte UTF-8 character.
26922  ** A single byte is required for the output string
26923  ** nul-terminator.
26924  */
26925  pMem->n &= ~1;
26926  len = pMem->n * 2 + 1;
26927  }else{
26928  /* When converting from UTF-8 to UTF-16 the maximum growth is caused
26929  ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
26930  ** character. Two bytes are required in the output buffer for the
26931  ** nul-terminator.
26932  */
26933  len = pMem->n * 2 + 2;
26934  }
26935 
26936  /* Set zIn to point at the start of the input buffer and zTerm to point 1
26937  ** byte past the end.
26938  **
26939  ** Variable zOut is set to point at the output buffer, space obtained
26940  ** from sqlite3_malloc().
26941  */
26942  zIn = (u8*)pMem->z;
26943  zTerm = &zIn[pMem->n];
26944  zOut = sqlite3DbMallocRaw(pMem->db, len);
26945  if( !zOut ){
26946  return SQLITE_NOMEM_BKPT;
26947  }
26948  z = zOut;
26949 
26950  if( pMem->enc==SQLITE_UTF8 ){
26951  if( desiredEnc==SQLITE_UTF16LE ){
26952  /* UTF-8 -> UTF-16 Little-endian */
26953  while( zIn<zTerm ){
26954  READ_UTF8(zIn, zTerm, c);
26955  WRITE_UTF16LE(z, c);
26956  }
26957  }else{
26958  assert( desiredEnc==SQLITE_UTF16BE );
26959  /* UTF-8 -> UTF-16 Big-endian */
26960  while( zIn<zTerm ){
26961  READ_UTF8(zIn, zTerm, c);
26962  WRITE_UTF16BE(z, c);
26963  }
26964  }
26965  pMem->n = (int)(z - zOut);
26966  *z++ = 0;
26967  }else{
26968  assert( desiredEnc==SQLITE_UTF8 );
26969  if( pMem->enc==SQLITE_UTF16LE ){
26970  /* UTF-16 Little-endian -> UTF-8 */
26971  while( zIn<zTerm ){
26972  READ_UTF16LE(zIn, zIn<zTerm, c);
26973  WRITE_UTF8(z, c);
26974  }
26975  }else{
26976  /* UTF-16 Big-endian -> UTF-8 */
26977  while( zIn<zTerm ){
26978  READ_UTF16BE(zIn, zIn<zTerm, c);
26979  WRITE_UTF8(z, c);
26980  }
26981  }
26982  pMem->n = (int)(z - zOut);
26983  }
26984  *z = 0;
26985  assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
26986 
26987  c = pMem->flags;
26988  sqlite3VdbeMemRelease(pMem);
26989  pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype));
26990  pMem->enc = desiredEnc;
26991  pMem->z = (char*)zOut;
26992  pMem->zMalloc = pMem->z;
26993  pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
26994 
26995 translate_out:
26996 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
26997  {
26998  char zBuf[100];
26999  sqlite3VdbeMemPrettyPrint(pMem, zBuf);
27000  fprintf(stderr, "OUTPUT: %s\n", zBuf);
27001  }
27002 #endif
27003  return SQLITE_OK;
27004 }
27005 
27006 /*
27007 ** This routine checks for a byte-order mark at the beginning of the
27008 ** UTF-16 string stored in *pMem. If one is present, it is removed and
27009 ** the encoding of the Mem adjusted. This routine does not do any
27010 ** byte-swapping, it just sets Mem.enc appropriately.
27011 **
27012 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
27013 ** changed by this function.
27014 */
27015 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
27016  int rc = SQLITE_OK;
27017  u8 bom = 0;
27018 
27019  assert( pMem->n>=0 );
27020  if( pMem->n>1 ){
27021  u8 b1 = *(u8 *)pMem->z;
27022  u8 b2 = *(((u8 *)pMem->z) + 1);
27023  if( b1==0xFE && b2==0xFF ){
27024  bom = SQLITE_UTF16BE;
27025  }
27026  if( b1==0xFF && b2==0xFE ){
27027  bom = SQLITE_UTF16LE;
27028  }
27029  }
27030 
27031  if( bom ){
27032  rc = sqlite3VdbeMemMakeWriteable(pMem);
27033  if( rc==SQLITE_OK ){
27034  pMem->n -= 2;
27035  memmove(pMem->z, &pMem->z[2], pMem->n);
27036  pMem->z[pMem->n] = '\0';
27037  pMem->z[pMem->n+1] = '\0';
27038  pMem->flags |= MEM_Term;
27039  pMem->enc = bom;
27040  }
27041  }
27042  return rc;
27043 }
27044 #endif /* SQLITE_OMIT_UTF16 */
27045 
27046 /*
27047 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
27048 ** return the number of unicode characters in pZ up to (but not including)
27049 ** the first 0x00 byte. If nByte is not less than zero, return the
27050 ** number of unicode characters in the first nByte of pZ (or up to
27051 ** the first 0x00, whichever comes first).
27052 */
27053 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
27054  int r = 0;
27055  const u8 *z = (const u8*)zIn;
27056  const u8 *zTerm;
27057  if( nByte>=0 ){
27058  zTerm = &z[nByte];
27059  }else{
27060  zTerm = (const u8*)(-1);
27061  }
27062  assert( z<=zTerm );
27063  while( *z!=0 && z<zTerm ){
27064  SQLITE_SKIP_UTF8(z);
27065  r++;
27066  }
27067  return r;
27068 }
27069 
27070 /* This test function is not currently used by the automated test-suite.
27071 ** Hence it is only available in debug builds.
27072 */
27073 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
27074 /*
27075 ** Translate UTF-8 to UTF-8.
27076 **
27077 ** This has the effect of making sure that the string is well-formed
27078 ** UTF-8. Miscoded characters are removed.
27079 **
27080 ** The translation is done in-place and aborted if the output
27081 ** overruns the input.
27082 */
27083 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
27084  unsigned char *zOut = zIn;
27085  unsigned char *zStart = zIn;
27086  u32 c;
27087 
27088  while( zIn[0] && zOut<=zIn ){
27089  c = sqlite3Utf8Read((const u8**)&zIn);
27090  if( c!=0xfffd ){
27091  WRITE_UTF8(zOut, c);
27092  }
27093  }
27094  *zOut = 0;
27095  return (int)(zOut - zStart);
27096 }
27097 #endif
27098 
27099 #ifndef SQLITE_OMIT_UTF16
27100 /*
27101 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
27102 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
27103 ** be freed by the calling function.
27104 **
27105 ** NULL is returned if there is an allocation error.
27106 */
27107 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
27108  Mem m;
27109  memset(&m, 0, sizeof(m));
27110  m.db = db;
27111  sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
27112  sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
27113  if( db->mallocFailed ){
27114  sqlite3VdbeMemRelease(&m);
27115  m.z = 0;
27116  }
27117  assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
27118  assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
27119  assert( m.z || db->mallocFailed );
27120  return m.z;
27121 }
27122 
27123 /*
27124 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
27125 ** Return the number of bytes in the first nChar unicode characters
27126 ** in pZ. nChar must be non-negative.
27127 */
27128 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
27129  int c;
27130  unsigned char const *z = zIn;
27131  int n = 0;
27132 
27133  if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
27134  while( n<nChar ){
27135  READ_UTF16BE(z, 1, c);
27136  n++;
27137  }
27138  }else{
27139  while( n<nChar ){
27140  READ_UTF16LE(z, 1, c);
27141  n++;
27142  }
27143  }
27144  return (int)(z-(unsigned char const *)zIn);
27145 }
27146 
27147 #if defined(SQLITE_TEST)
27148 /*
27149 ** This routine is called from the TCL test function "translate_selftest".
27150 ** It checks that the primitives for serializing and deserializing
27151 ** characters in each encoding are inverses of each other.
27152 */
27153 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
27154  unsigned int i, t;
27155  unsigned char zBuf[20];
27156  unsigned char *z;
27157  int n;
27158  unsigned int c;
27159 
27160  for(i=0; i<0x00110000; i++){
27161  z = zBuf;
27162  WRITE_UTF8(z, i);
27163  n = (int)(z-zBuf);
27164  assert( n>0 && n<=4 );
27165  z[0] = 0;
27166  z = zBuf;
27167  c = sqlite3Utf8Read((const u8**)&z);
27168  t = i;
27169  if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
27170  if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
27171  assert( c==t );
27172  assert( (z-zBuf)==n );
27173  }
27174  for(i=0; i<0x00110000; i++){
27175  if( i>=0xD800 && i<0xE000 ) continue;
27176  z = zBuf;
27177  WRITE_UTF16LE(z, i);
27178  n = (int)(z-zBuf);
27179  assert( n>0 && n<=4 );
27180  z[0] = 0;
27181  z = zBuf;
27182  READ_UTF16LE(z, 1, c);
27183  assert( c==i );
27184  assert( (z-zBuf)==n );
27185  }
27186  for(i=0; i<0x00110000; i++){
27187  if( i>=0xD800 && i<0xE000 ) continue;
27188  z = zBuf;
27189  WRITE_UTF16BE(z, i);
27190  n = (int)(z-zBuf);
27191  assert( n>0 && n<=4 );
27192  z[0] = 0;
27193  z = zBuf;
27194  READ_UTF16BE(z, 1, c);
27195  assert( c==i );
27196  assert( (z-zBuf)==n );
27197  }
27198 }
27199 #endif /* SQLITE_TEST */
27200 #endif /* SQLITE_OMIT_UTF16 */
27201 
27202 /************** End of utf.c *************************************************/
27203 /************** Begin file util.c ********************************************/
27204 /*
27205 ** 2001 September 15
27206 **
27207 ** The author disclaims copyright to this source code. In place of
27208 ** a legal notice, here is a blessing:
27209 **
27210 ** May you do good and not evil.
27211 ** May you find forgiveness for yourself and forgive others.
27212 ** May you share freely, never taking more than you give.
27213 **
27214 *************************************************************************
27215 ** Utility functions used throughout sqlite.
27216 **
27217 ** This file contains functions for allocating memory, comparing
27218 ** strings, and stuff like that.
27219 **
27220 */
27221 /* #include "sqliteInt.h" */
27222 /* #include <stdarg.h> */
27223 #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
27224 # include <math.h>
27225 #endif
27226 
27227 /*
27228 ** Routine needed to support the testcase() macro.
27229 */
27230 #ifdef SQLITE_COVERAGE_TEST
27231 SQLITE_PRIVATE void sqlite3Coverage(int x){
27232  static unsigned dummy = 0;
27233  dummy += (unsigned)x;
27234 }
27235 #endif
27236 
27237 /*
27238 ** Give a callback to the test harness that can be used to simulate faults
27239 ** in places where it is difficult or expensive to do so purely by means
27240 ** of inputs.
27241 **
27242 ** The intent of the integer argument is to let the fault simulator know
27243 ** which of multiple sqlite3FaultSim() calls has been hit.
27244 **
27245 ** Return whatever integer value the test callback returns, or return
27246 ** SQLITE_OK if no test callback is installed.
27247 */
27248 #ifndef SQLITE_OMIT_BUILTIN_TEST
27249 SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
27250  int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
27251  return xCallback ? xCallback(iTest) : SQLITE_OK;
27252 }
27253 #endif
27254 
27255 #ifndef SQLITE_OMIT_FLOATING_POINT
27256 /*
27257 ** Return true if the floating point value is Not a Number (NaN).
27258 **
27259 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
27260 ** Otherwise, we have our own implementation that works on most systems.
27261 */
27262 SQLITE_PRIVATE int sqlite3IsNaN(double x){
27263  int rc; /* The value return */
27264 #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
27265  /*
27266  ** Systems that support the isnan() library function should probably
27267  ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
27268  ** found that many systems do not have a working isnan() function so
27269  ** this implementation is provided as an alternative.
27270  **
27271  ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
27272  ** On the other hand, the use of -ffast-math comes with the following
27273  ** warning:
27274  **
27275  ** This option [-ffast-math] should never be turned on by any
27276  ** -O option since it can result in incorrect output for programs
27277  ** which depend on an exact implementation of IEEE or ISO
27278  ** rules/specifications for math functions.
27279  **
27280  ** Under MSVC, this NaN test may fail if compiled with a floating-
27281  ** point precision mode other than /fp:precise. From the MSDN
27282  ** documentation:
27283  **
27284  ** The compiler [with /fp:precise] will properly handle comparisons
27285  ** involving NaN. For example, x != x evaluates to true if x is NaN
27286  ** ...
27287  */
27288 #ifdef __FAST_MATH__
27289 # error SQLite will not work correctly with the -ffast-math option of GCC.
27290 #endif
27291  volatile double y = x;
27292  volatile double z = y;
27293  rc = (y!=z);
27294 #else /* if HAVE_ISNAN */
27295  rc = isnan(x);
27296 #endif /* HAVE_ISNAN */
27297  testcase( rc );
27298  return rc;
27299 }
27300 #endif /* SQLITE_OMIT_FLOATING_POINT */
27301 
27302 /*
27303 ** Compute a string length that is limited to what can be stored in
27304 ** lower 30 bits of a 32-bit signed integer.
27305 **
27306 ** The value returned will never be negative. Nor will it ever be greater
27307 ** than the actual length of the string. For very long strings (greater
27308 ** than 1GiB) the value returned might be less than the true string length.
27309 */
27310 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
27311  if( z==0 ) return 0;
27312  return 0x3fffffff & (int)strlen(z);
27313 }
27314 
27315 /*
27316 ** Return the declared type of a column. Or return zDflt if the column
27317 ** has no declared type.
27318 **
27319 ** The column type is an extra string stored after the zero-terminator on
27320 ** the column name if and only if the COLFLAG_HASTYPE flag is set.
27321 */
27322 SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
27323  if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
27324  return pCol->zName + strlen(pCol->zName) + 1;
27325 }
27326 
27327 /*
27328 ** Helper function for sqlite3Error() - called rarely. Broken out into
27329 ** a separate routine to avoid unnecessary register saves on entry to
27330 ** sqlite3Error().
27331 */
27332 static SQLITE_NOINLINE void sqlite3ErrorFinish(sqlite3 *db, int err_code){
27333  if( db->pErr ) sqlite3ValueSetNull(db->pErr);
27334  sqlite3SystemError(db, err_code);
27335 }
27336 
27337 /*
27338 ** Set the current error code to err_code and clear any prior error message.
27339 ** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
27340 ** that would be appropriate.
27341 */
27342 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
27343  assert( db!=0 );
27344  db->errCode = err_code;
27345  if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
27346 }
27347 
27348 /*
27349 ** Load the sqlite3.iSysErrno field if that is an appropriate thing
27350 ** to do based on the SQLite error code in rc.
27351 */
27352 SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
27353  if( rc==SQLITE_IOERR_NOMEM ) return;
27354  rc &= 0xff;
27355  if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
27356  db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
27357  }
27358 }
27359 
27360 /*
27361 ** Set the most recent error code and error string for the sqlite
27362 ** handle "db". The error code is set to "err_code".
27363 **
27364 ** If it is not NULL, string zFormat specifies the format of the
27365 ** error string in the style of the printf functions: The following
27366 ** format characters are allowed:
27367 **
27368 ** %s Insert a string
27369 ** %z A string that should be freed after use
27370 ** %d Insert an integer
27371 ** %T Insert a token
27372 ** %S Insert the first element of a SrcList
27373 **
27374 ** zFormat and any string tokens that follow it are assumed to be
27375 ** encoded in UTF-8.
27376 **
27377 ** To clear the most recent error for sqlite handle "db", sqlite3Error
27378 ** should be called with err_code set to SQLITE_OK and zFormat set
27379 ** to NULL.
27380 */
27381 SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
27382  assert( db!=0 );
27383  db->errCode = err_code;
27384  sqlite3SystemError(db, err_code);
27385  if( zFormat==0 ){
27386  sqlite3Error(db, err_code);
27387  }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
27388  char *z;
27389  va_list ap;
27390  va_start(ap, zFormat);
27391  z = sqlite3VMPrintf(db, zFormat, ap);
27392  va_end(ap);
27393  sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
27394  }
27395 }
27396 
27397 /*
27398 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
27399 ** The following formatting characters are allowed:
27400 **
27401 ** %s Insert a string
27402 ** %z A string that should be freed after use
27403 ** %d Insert an integer
27404 ** %T Insert a token
27405 ** %S Insert the first element of a SrcList
27406 **
27407 ** This function should be used to report any error that occurs while
27408 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
27409 ** last thing the sqlite3_prepare() function does is copy the error
27410 ** stored by this function into the database handle using sqlite3Error().
27411 ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
27412 ** during statement execution (sqlite3_step() etc.).
27413 */
27414 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
27415  char *zMsg;
27416  va_list ap;
27417  sqlite3 *db = pParse->db;
27418  va_start(ap, zFormat);
27419  zMsg = sqlite3VMPrintf(db, zFormat, ap);
27420  va_end(ap);
27421  if( db->suppressErr ){
27422  sqlite3DbFree(db, zMsg);
27423  }else{
27424  pParse->nErr++;
27425  sqlite3DbFree(db, pParse->zErrMsg);
27426  pParse->zErrMsg = zMsg;
27427  pParse->rc = SQLITE_ERROR;
27428  }
27429 }
27430 
27431 /*
27432 ** Convert an SQL-style quoted string into a normal string by removing
27433 ** the quote characters. The conversion is done in-place. If the
27434 ** input does not begin with a quote character, then this routine
27435 ** is a no-op.
27436 **
27437 ** The input string must be zero-terminated. A new zero-terminator
27438 ** is added to the dequoted string.
27439 **
27440 ** The return value is -1 if no dequoting occurs or the length of the
27441 ** dequoted string, exclusive of the zero terminator, if dequoting does
27442 ** occur.
27443 **
27444 ** 2002-Feb-14: This routine is extended to remove MS-Access style
27445 ** brackets from around identifiers. For example: "[a-b-c]" becomes
27446 ** "a-b-c".
27447 */
27448 SQLITE_PRIVATE void sqlite3Dequote(char *z){
27449  char quote;
27450  int i, j;
27451  if( z==0 ) return;
27452  quote = z[0];
27453  if( !sqlite3Isquote(quote) ) return;
27454  if( quote=='[' ) quote = ']';
27455  for(i=1, j=0;; i++){
27456  assert( z[i] );
27457  if( z[i]==quote ){
27458  if( z[i+1]==quote ){
27459  z[j++] = quote;
27460  i++;
27461  }else{
27462  break;
27463  }
27464  }else{
27465  z[j++] = z[i];
27466  }
27467  }
27468  z[j] = 0;
27469 }
27470 
27471 /*
27472 ** Generate a Token object from a string
27473 */
27474 SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){
27475  p->z = z;
27476  p->n = sqlite3Strlen30(z);
27477 }
27478 
27479 /* Convenient short-hand */
27480 #define UpperToLower sqlite3UpperToLower
27481 
27482 /*
27483 ** Some systems have stricmp(). Others have strcasecmp(). Because
27484 ** there is no consistency, we will define our own.
27485 **
27486 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
27487 ** sqlite3_strnicmp() APIs allow applications and extensions to compare
27488 ** the contents of two buffers containing UTF-8 strings in a
27489 ** case-independent fashion, using the same definition of "case
27490 ** independence" that SQLite uses internally when comparing identifiers.
27491 */
27492 SQLITE_API int SQLITE_STDCALL sqlite3_stricmp(const char *zLeft, const char *zRight){
27493  if( zLeft==0 ){
27494  return zRight ? -1 : 0;
27495  }else if( zRight==0 ){
27496  return 1;
27497  }
27498  return sqlite3StrICmp(zLeft, zRight);
27499 }
27500 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
27501  unsigned char *a, *b;
27502  int c;
27503  a = (unsigned char *)zLeft;
27504  b = (unsigned char *)zRight;
27505  for(;;){
27506  c = (int)UpperToLower[*a] - (int)UpperToLower[*b];
27507  if( c || *a==0 ) break;
27508  a++;
27509  b++;
27510  }
27511  return c;
27512 }
27513 SQLITE_API int SQLITE_STDCALL sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
27514  register unsigned char *a, *b;
27515  if( zLeft==0 ){
27516  return zRight ? -1 : 0;
27517  }else if( zRight==0 ){
27518  return 1;
27519  }
27520  a = (unsigned char *)zLeft;
27521  b = (unsigned char *)zRight;
27522  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
27523  return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
27524 }
27525 
27526 /*
27527 ** The string z[] is an text representation of a real number.
27528 ** Convert this string to a double and write it into *pResult.
27529 **
27530 ** The string z[] is length bytes in length (bytes, not characters) and
27531 ** uses the encoding enc. The string is not necessarily zero-terminated.
27532 **
27533 ** Return TRUE if the result is a valid real number (or integer) and FALSE
27534 ** if the string is empty or contains extraneous text. Valid numbers
27535 ** are in one of these formats:
27536 **
27537 ** [+-]digits[E[+-]digits]
27538 ** [+-]digits.[digits][E[+-]digits]
27539 ** [+-].digits[E[+-]digits]
27540 **
27541 ** Leading and trailing whitespace is ignored for the purpose of determining
27542 ** validity.
27543 **
27544 ** If some prefix of the input string is a valid number, this routine
27545 ** returns FALSE but it still converts the prefix and writes the result
27546 ** into *pResult.
27547 */
27548 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
27549 #ifndef SQLITE_OMIT_FLOATING_POINT
27550  int incr;
27551  const char *zEnd = z + length;
27552  /* sign * significand * (10 ^ (esign * exponent)) */
27553  int sign = 1; /* sign of significand */
27554  i64 s = 0; /* significand */
27555  int d = 0; /* adjust exponent for shifting decimal point */
27556  int esign = 1; /* sign of exponent */
27557  int e = 0; /* exponent */
27558  int eValid = 1; /* True exponent is either not used or is well-formed */
27559  double result;
27560  int nDigits = 0;
27561  int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
27562 
27563  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
27564  *pResult = 0.0; /* Default return value, in case of an error */
27565 
27566  if( enc==SQLITE_UTF8 ){
27567  incr = 1;
27568  }else{
27569  int i;
27570  incr = 2;
27571  assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
27572  for(i=3-enc; i<length && z[i]==0; i+=2){}
27573  nonNum = i<length;
27574  zEnd = &z[i^1];
27575  z += (enc&1);
27576  }
27577 
27578  /* skip leading spaces */
27579  while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
27580  if( z>=zEnd ) return 0;
27581 
27582  /* get sign of significand */
27583  if( *z=='-' ){
27584  sign = -1;
27585  z+=incr;
27586  }else if( *z=='+' ){
27587  z+=incr;
27588  }
27589 
27590  /* copy max significant digits to significand */
27591  while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
27592  s = s*10 + (*z - '0');
27593  z+=incr, nDigits++;
27594  }
27595 
27596  /* skip non-significant significand digits
27597  ** (increase exponent by d to shift decimal left) */
27598  while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
27599  if( z>=zEnd ) goto do_atof_calc;
27600 
27601  /* if decimal point is present */
27602  if( *z=='.' ){
27603  z+=incr;
27604  /* copy digits from after decimal to significand
27605  ** (decrease exponent by d to shift decimal right) */
27606  while( z<zEnd && sqlite3Isdigit(*z) ){
27607  if( s<((LARGEST_INT64-9)/10) ){
27608  s = s*10 + (*z - '0');
27609  d--;
27610  }
27611  z+=incr, nDigits++;
27612  }
27613  }
27614  if( z>=zEnd ) goto do_atof_calc;
27615 
27616  /* if exponent is present */
27617  if( *z=='e' || *z=='E' ){
27618  z+=incr;
27619  eValid = 0;
27620 
27621  /* This branch is needed to avoid a (harmless) buffer overread. The
27622  ** special comment alerts the mutation tester that the correct answer
27623  ** is obtained even if the branch is omitted */
27624  if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/
27625 
27626  /* get sign of exponent */
27627  if( *z=='-' ){
27628  esign = -1;
27629  z+=incr;
27630  }else if( *z=='+' ){
27631  z+=incr;
27632  }
27633  /* copy digits to exponent */
27634  while( z<zEnd && sqlite3Isdigit(*z) ){
27635  e = e<10000 ? (e*10 + (*z - '0')) : 10000;
27636  z+=incr;
27637  eValid = 1;
27638  }
27639  }
27640 
27641  /* skip trailing spaces */
27642  while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
27643 
27644 do_atof_calc:
27645  /* adjust exponent by d, and update sign */
27646  e = (e*esign) + d;
27647  if( e<0 ) {
27648  esign = -1;
27649  e *= -1;
27650  } else {
27651  esign = 1;
27652  }
27653 
27654  if( s==0 ) {
27655  /* In the IEEE 754 standard, zero is signed. */
27656  result = sign<0 ? -(double)0 : (double)0;
27657  } else {
27658  /* Attempt to reduce exponent.
27659  **
27660  ** Branches that are not required for the correct answer but which only
27661  ** help to obtain the correct answer faster are marked with special
27662  ** comments, as a hint to the mutation tester.
27663  */
27664  while( e>0 ){ /*OPTIMIZATION-IF-TRUE*/
27665  if( esign>0 ){
27666  if( s>=(LARGEST_INT64/10) ) break; /*OPTIMIZATION-IF-FALSE*/
27667  s *= 10;
27668  }else{
27669  if( s%10!=0 ) break; /*OPTIMIZATION-IF-FALSE*/
27670  s /= 10;
27671  }
27672  e--;
27673  }
27674 
27675  /* adjust the sign of significand */
27676  s = sign<0 ? -s : s;
27677 
27678  if( e==0 ){ /*OPTIMIZATION-IF-TRUE*/
27679  result = (double)s;
27680  }else{
27681  LONGDOUBLE_TYPE scale = 1.0;
27682  /* attempt to handle extremely small/large numbers better */
27683  if( e>307 ){ /*OPTIMIZATION-IF-TRUE*/
27684  if( e<342 ){ /*OPTIMIZATION-IF-TRUE*/
27685  while( e%308 ) { scale *= 1.0e+1; e -= 1; }
27686  if( esign<0 ){
27687  result = s / scale;
27688  result /= 1.0e+308;
27689  }else{
27690  result = s * scale;
27691  result *= 1.0e+308;
27692  }
27693  }else{ assert( e>=342 );
27694  if( esign<0 ){
27695  result = 0.0*s;
27696  }else{
27697  result = 1e308*1e308*s; /* Infinity */
27698  }
27699  }
27700  }else{
27701  /* 1.0e+22 is the largest power of 10 than can be
27702  ** represented exactly. */
27703  while( e%22 ) { scale *= 1.0e+1; e -= 1; }
27704  while( e>0 ) { scale *= 1.0e+22; e -= 22; }
27705  if( esign<0 ){
27706  result = s / scale;
27707  }else{
27708  result = s * scale;
27709  }
27710  }
27711  }
27712  }
27713 
27714  /* store the result */
27715  *pResult = result;
27716 
27717  /* return true if number and no extra non-whitespace chracters after */
27718  return z==zEnd && nDigits>0 && eValid && nonNum==0;
27719 #else
27720  return !sqlite3Atoi64(z, pResult, length, enc);
27721 #endif /* SQLITE_OMIT_FLOATING_POINT */
27722 }
27723 
27724 /*
27725 ** Compare the 19-character string zNum against the text representation
27726 ** value 2^63: 9223372036854775808. Return negative, zero, or positive
27727 ** if zNum is less than, equal to, or greater than the string.
27728 ** Note that zNum must contain exactly 19 characters.
27729 **
27730 ** Unlike memcmp() this routine is guaranteed to return the difference
27731 ** in the values of the last digit if the only difference is in the
27732 ** last digit. So, for example,
27733 **
27734 ** compare2pow63("9223372036854775800", 1)
27735 **
27736 ** will return -8.
27737 */
27738 static int compare2pow63(const char *zNum, int incr){
27739  int c = 0;
27740  int i;
27741  /* 012345678901234567 */
27742  const char *pow63 = "922337203685477580";
27743  for(i=0; c==0 && i<18; i++){
27744  c = (zNum[i*incr]-pow63[i])*10;
27745  }
27746  if( c==0 ){
27747  c = zNum[18*incr] - '8';
27748  testcase( c==(-1) );
27749  testcase( c==0 );
27750  testcase( c==(+1) );
27751  }
27752  return c;
27753 }
27754 
27755 /*
27756 ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
27757 ** routine does *not* accept hexadecimal notation.
27758 **
27759 ** If the zNum value is representable as a 64-bit twos-complement
27760 ** integer, then write that value into *pNum and return 0.
27761 **
27762 ** If zNum is exactly 9223372036854775808, return 2. This special
27763 ** case is broken out because while 9223372036854775808 cannot be a
27764 ** signed 64-bit integer, its negative -9223372036854775808 can be.
27765 **
27766 ** If zNum is too big for a 64-bit integer and is not
27767 ** 9223372036854775808 or if zNum contains any non-numeric text,
27768 ** then return 1.
27769 **
27770 ** length is the number of bytes in the string (bytes, not characters).
27771 ** The string is not necessarily zero-terminated. The encoding is
27772 ** given by enc.
27773 */
27774 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
27775  int incr;
27776  u64 u = 0;
27777  int neg = 0; /* assume positive */
27778  int i;
27779  int c = 0;
27780  int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
27781  const char *zStart;
27782  const char *zEnd = zNum + length;
27783  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
27784  if( enc==SQLITE_UTF8 ){
27785  incr = 1;
27786  }else{
27787  incr = 2;
27788  assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
27789  for(i=3-enc; i<length && zNum[i]==0; i+=2){}
27790  nonNum = i<length;
27791  zEnd = &zNum[i^1];
27792  zNum += (enc&1);
27793  }
27794  while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
27795  if( zNum<zEnd ){
27796  if( *zNum=='-' ){
27797  neg = 1;
27798  zNum+=incr;
27799  }else if( *zNum=='+' ){
27800  zNum+=incr;
27801  }
27802  }
27803  zStart = zNum;
27804  while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
27805  for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
27806  u = u*10 + c - '0';
27807  }
27808  if( u>LARGEST_INT64 ){
27809  *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
27810  }else if( neg ){
27811  *pNum = -(i64)u;
27812  }else{
27813  *pNum = (i64)u;
27814  }
27815  testcase( i==18 );
27816  testcase( i==19 );
27817  testcase( i==20 );
27818  if( &zNum[i]<zEnd /* Extra bytes at the end */
27819  || (i==0 && zStart==zNum) /* No digits */
27820  || i>19*incr /* Too many digits */
27821  || nonNum /* UTF16 with high-order bytes non-zero */
27822  ){
27823  /* zNum is empty or contains non-numeric text or is longer
27824  ** than 19 digits (thus guaranteeing that it is too large) */
27825  return 1;
27826  }else if( i<19*incr ){
27827  /* Less than 19 digits, so we know that it fits in 64 bits */
27828  assert( u<=LARGEST_INT64 );
27829  return 0;
27830  }else{
27831  /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
27832  c = compare2pow63(zNum, incr);
27833  if( c<0 ){
27834  /* zNum is less than 9223372036854775808 so it fits */
27835  assert( u<=LARGEST_INT64 );
27836  return 0;
27837  }else if( c>0 ){
27838  /* zNum is greater than 9223372036854775808 so it overflows */
27839  return 1;
27840  }else{
27841  /* zNum is exactly 9223372036854775808. Fits if negative. The
27842  ** special case 2 overflow if positive */
27843  assert( u-1==LARGEST_INT64 );
27844  return neg ? 0 : 2;
27845  }
27846  }
27847 }
27848 
27849 /*
27850 ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
27851 ** into a 64-bit signed integer. This routine accepts hexadecimal literals,
27852 ** whereas sqlite3Atoi64() does not.
27853 **
27854 ** Returns:
27855 **
27856 ** 0 Successful transformation. Fits in a 64-bit signed integer.
27857 ** 1 Integer too large for a 64-bit signed integer or is malformed
27858 ** 2 Special case of 9223372036854775808
27859 */
27860 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
27861 #ifndef SQLITE_OMIT_HEX_INTEGER
27862  if( z[0]=='0'
27863  && (z[1]=='x' || z[1]=='X')
27864  ){
27865  u64 u = 0;
27866  int i, k;
27867  for(i=2; z[i]=='0'; i++){}
27868  for(k=i; sqlite3Isxdigit(z[k]); k++){
27869  u = u*16 + sqlite3HexToInt(z[k]);
27870  }
27871  memcpy(pOut, &u, 8);
27872  return (z[k]==0 && k-i<=16) ? 0 : 1;
27873  }else
27874 #endif /* SQLITE_OMIT_HEX_INTEGER */
27875  {
27876  return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
27877  }
27878 }
27879 
27880 /*
27881 ** If zNum represents an integer that will fit in 32-bits, then set
27882 ** *pValue to that integer and return true. Otherwise return false.
27883 **
27884 ** This routine accepts both decimal and hexadecimal notation for integers.
27885 **
27886 ** Any non-numeric characters that following zNum are ignored.
27887 ** This is different from sqlite3Atoi64() which requires the
27888 ** input number to be zero-terminated.
27889 */
27890 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
27891  sqlite_int64 v = 0;
27892  int i, c;
27893  int neg = 0;
27894  if( zNum[0]=='-' ){
27895  neg = 1;
27896  zNum++;
27897  }else if( zNum[0]=='+' ){
27898  zNum++;
27899  }
27900 #ifndef SQLITE_OMIT_HEX_INTEGER
27901  else if( zNum[0]=='0'
27902  && (zNum[1]=='x' || zNum[1]=='X')
27903  && sqlite3Isxdigit(zNum[2])
27904  ){
27905  u32 u = 0;
27906  zNum += 2;
27907  while( zNum[0]=='0' ) zNum++;
27908  for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
27909  u = u*16 + sqlite3HexToInt(zNum[i]);
27910  }
27911  if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
27912  memcpy(pValue, &u, 4);
27913  return 1;
27914  }else{
27915  return 0;
27916  }
27917  }
27918 #endif
27919  while( zNum[0]=='0' ) zNum++;
27920  for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
27921  v = v*10 + c;
27922  }
27923 
27924  /* The longest decimal representation of a 32 bit integer is 10 digits:
27925  **
27926  ** 1234567890
27927  ** 2^31 -> 2147483648
27928  */
27929  testcase( i==10 );
27930  if( i>10 ){
27931  return 0;
27932  }
27933  testcase( v-neg==2147483647 );
27934  if( v-neg>2147483647 ){
27935  return 0;
27936  }
27937  if( neg ){
27938  v = -v;
27939  }
27940  *pValue = (int)v;
27941  return 1;
27942 }
27943 
27944 /*
27945 ** Return a 32-bit integer value extracted from a string. If the
27946 ** string is not an integer, just return 0.
27947 */
27948 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
27949  int x = 0;
27950  if( z ) sqlite3GetInt32(z, &x);
27951  return x;
27952 }
27953 
27954 /*
27955 ** The variable-length integer encoding is as follows:
27956 **
27957 ** KEY:
27958 ** A = 0xxxxxxx 7 bits of data and one flag bit
27959 ** B = 1xxxxxxx 7 bits of data and one flag bit
27960 ** C = xxxxxxxx 8 bits of data
27961 **
27962 ** 7 bits - A
27963 ** 14 bits - BA
27964 ** 21 bits - BBA
27965 ** 28 bits - BBBA
27966 ** 35 bits - BBBBA
27967 ** 42 bits - BBBBBA
27968 ** 49 bits - BBBBBBA
27969 ** 56 bits - BBBBBBBA
27970 ** 64 bits - BBBBBBBBC
27971 */
27972 
27973 /*
27974 ** Write a 64-bit variable-length integer to memory starting at p[0].
27975 ** The length of data write will be between 1 and 9 bytes. The number
27976 ** of bytes written is returned.
27977 **
27978 ** A variable-length integer consists of the lower 7 bits of each byte
27979 ** for all bytes that have the 8th bit set and one byte with the 8th
27980 ** bit clear. Except, if we get to the 9th byte, it stores the full
27981 ** 8 bits and is the last byte.
27982 */
27983 static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
27984  int i, j, n;
27985  u8 buf[10];
27986  if( v & (((u64)0xff000000)<<32) ){
27987  p[8] = (u8)v;
27988  v >>= 8;
27989  for(i=7; i>=0; i--){
27990  p[i] = (u8)((v & 0x7f) | 0x80);
27991  v >>= 7;
27992  }
27993  return 9;
27994  }
27995  n = 0;
27996  do{
27997  buf[n++] = (u8)((v & 0x7f) | 0x80);
27998  v >>= 7;
27999  }while( v!=0 );
28000  buf[0] &= 0x7f;
28001  assert( n<=9 );
28002  for(i=0, j=n-1; j>=0; j--, i++){
28003  p[i] = buf[j];
28004  }
28005  return n;
28006 }
28007 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
28008  if( v<=0x7f ){
28009  p[0] = v&0x7f;
28010  return 1;
28011  }
28012  if( v<=0x3fff ){
28013  p[0] = ((v>>7)&0x7f)|0x80;
28014  p[1] = v&0x7f;
28015  return 2;
28016  }
28017  return putVarint64(p,v);
28018 }
28019 
28020 /*
28021 ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
28022 ** are defined here rather than simply putting the constant expressions
28023 ** inline in order to work around bugs in the RVT compiler.
28024 **
28025 ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
28026 **
28027 ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
28028 */
28029 #define SLOT_2_0 0x001fc07f
28030 #define SLOT_4_2_0 0xf01fc07f
28031 
28032 
28033 /*
28034 ** Read a 64-bit variable-length integer from memory starting at p[0].
28035 ** Return the number of bytes read. The value is stored in *v.
28036 */
28037 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
28038  u32 a,b,s;
28039 
28040  a = *p;
28041  /* a: p0 (unmasked) */
28042  if (!(a&0x80))
28043  {
28044  *v = a;
28045  return 1;
28046  }
28047 
28048  p++;
28049  b = *p;
28050  /* b: p1 (unmasked) */
28051  if (!(b&0x80))
28052  {
28053  a &= 0x7f;
28054  a = a<<7;
28055  a |= b;
28056  *v = a;
28057  return 2;
28058  }
28059 
28060  /* Verify that constants are precomputed correctly */
28061  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
28062  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
28063 
28064  p++;
28065  a = a<<14;
28066  a |= *p;
28067  /* a: p0<<14 | p2 (unmasked) */
28068  if (!(a&0x80))
28069  {
28070  a &= SLOT_2_0;
28071  b &= 0x7f;
28072  b = b<<7;
28073  a |= b;
28074  *v = a;
28075  return 3;
28076  }
28077 
28078  /* CSE1 from below */
28079  a &= SLOT_2_0;
28080  p++;
28081  b = b<<14;
28082  b |= *p;
28083  /* b: p1<<14 | p3 (unmasked) */
28084  if (!(b&0x80))
28085  {
28086  b &= SLOT_2_0;
28087  /* moved CSE1 up */
28088  /* a &= (0x7f<<14)|(0x7f); */
28089  a = a<<7;
28090  a |= b;
28091  *v = a;
28092  return 4;
28093  }
28094 
28095  /* a: p0<<14 | p2 (masked) */
28096  /* b: p1<<14 | p3 (unmasked) */
28097  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
28098  /* moved CSE1 up */
28099  /* a &= (0x7f<<14)|(0x7f); */
28100  b &= SLOT_2_0;
28101  s = a;
28102  /* s: p0<<14 | p2 (masked) */
28103 
28104  p++;
28105  a = a<<14;
28106  a |= *p;
28107  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
28108  if (!(a&0x80))
28109  {
28110  /* we can skip these cause they were (effectively) done above
28111  ** while calculating s */
28112  /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
28113  /* b &= (0x7f<<14)|(0x7f); */
28114  b = b<<7;
28115  a |= b;
28116  s = s>>18;
28117  *v = ((u64)s)<<32 | a;
28118  return 5;
28119  }
28120 
28121  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
28122  s = s<<7;
28123  s |= b;
28124  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
28125 
28126  p++;
28127  b = b<<14;
28128  b |= *p;
28129  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
28130  if (!(b&0x80))
28131  {
28132  /* we can skip this cause it was (effectively) done above in calc'ing s */
28133  /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
28134  a &= SLOT_2_0;
28135  a = a<<7;
28136  a |= b;
28137  s = s>>18;
28138  *v = ((u64)s)<<32 | a;
28139  return 6;
28140  }
28141 
28142  p++;
28143  a = a<<14;
28144  a |= *p;
28145  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
28146  if (!(a&0x80))
28147  {
28148  a &= SLOT_4_2_0;
28149  b &= SLOT_2_0;
28150  b = b<<7;
28151  a |= b;
28152  s = s>>11;
28153  *v = ((u64)s)<<32 | a;
28154  return 7;
28155  }
28156 
28157  /* CSE2 from below */
28158  a &= SLOT_2_0;
28159  p++;
28160  b = b<<14;
28161  b |= *p;
28162  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
28163  if (!(b&0x80))
28164  {
28165  b &= SLOT_4_2_0;
28166  /* moved CSE2 up */
28167  /* a &= (0x7f<<14)|(0x7f); */
28168  a = a<<7;
28169  a |= b;
28170  s = s>>4;
28171  *v = ((u64)s)<<32 | a;
28172  return 8;
28173  }
28174 
28175  p++;
28176  a = a<<15;
28177  a |= *p;
28178  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
28179 
28180  /* moved CSE2 up */
28181  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
28182  b &= SLOT_2_0;
28183  b = b<<8;
28184  a |= b;
28185 
28186  s = s<<4;
28187  b = p[-4];
28188  b &= 0x7f;
28189  b = b>>3;
28190  s |= b;
28191 
28192  *v = ((u64)s)<<32 | a;
28193 
28194  return 9;
28195 }
28196 
28197 /*
28198 ** Read a 32-bit variable-length integer from memory starting at p[0].
28199 ** Return the number of bytes read. The value is stored in *v.
28200 **
28201 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
28202 ** integer, then set *v to 0xffffffff.
28203 **
28204 ** A MACRO version, getVarint32, is provided which inlines the
28205 ** single-byte case. All code should use the MACRO version as
28206 ** this function assumes the single-byte case has already been handled.
28207 */
28208 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
28209  u32 a,b;
28210 
28211  /* The 1-byte case. Overwhelmingly the most common. Handled inline
28212  ** by the getVarin32() macro */
28213  a = *p;
28214  /* a: p0 (unmasked) */
28215 #ifndef getVarint32
28216  if (!(a&0x80))
28217  {
28218  /* Values between 0 and 127 */
28219  *v = a;
28220  return 1;
28221  }
28222 #endif
28223 
28224  /* The 2-byte case */
28225  p++;
28226  b = *p;
28227  /* b: p1 (unmasked) */
28228  if (!(b&0x80))
28229  {
28230  /* Values between 128 and 16383 */
28231  a &= 0x7f;
28232  a = a<<7;
28233  *v = a | b;
28234  return 2;
28235  }
28236 
28237  /* The 3-byte case */
28238  p++;
28239  a = a<<14;
28240  a |= *p;
28241  /* a: p0<<14 | p2 (unmasked) */
28242  if (!(a&0x80))
28243  {
28244  /* Values between 16384 and 2097151 */
28245  a &= (0x7f<<14)|(0x7f);
28246  b &= 0x7f;
28247  b = b<<7;
28248  *v = a | b;
28249  return 3;
28250  }
28251 
28252  /* A 32-bit varint is used to store size information in btrees.
28253  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
28254  ** A 3-byte varint is sufficient, for example, to record the size
28255  ** of a 1048569-byte BLOB or string.
28256  **
28257  ** We only unroll the first 1-, 2-, and 3- byte cases. The very
28258  ** rare larger cases can be handled by the slower 64-bit varint
28259  ** routine.
28260  */
28261 #if 1
28262  {
28263  u64 v64;
28264  u8 n;
28265 
28266  p -= 2;
28267  n = sqlite3GetVarint(p, &v64);
28268  assert( n>3 && n<=9 );
28269  if( (v64 & SQLITE_MAX_U32)!=v64 ){
28270  *v = 0xffffffff;
28271  }else{
28272  *v = (u32)v64;
28273  }
28274  return n;
28275  }
28276 
28277 #else
28278  /* For following code (kept for historical record only) shows an
28279  ** unrolling for the 3- and 4-byte varint cases. This code is
28280  ** slightly faster, but it is also larger and much harder to test.
28281  */
28282  p++;
28283  b = b<<14;
28284  b |= *p;
28285  /* b: p1<<14 | p3 (unmasked) */
28286  if (!(b&0x80))
28287  {
28288  /* Values between 2097152 and 268435455 */
28289  b &= (0x7f<<14)|(0x7f);
28290  a &= (0x7f<<14)|(0x7f);
28291  a = a<<7;
28292  *v = a | b;
28293  return 4;
28294  }
28295 
28296  p++;
28297  a = a<<14;
28298  a |= *p;
28299  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
28300  if (!(a&0x80))
28301  {
28302  /* Values between 268435456 and 34359738367 */
28303  a &= SLOT_4_2_0;
28304  b &= SLOT_4_2_0;
28305  b = b<<7;
28306  *v = a | b;
28307  return 5;
28308  }
28309 
28310  /* We can only reach this point when reading a corrupt database
28311  ** file. In that case we are not in any hurry. Use the (relatively
28312  ** slow) general-purpose sqlite3GetVarint() routine to extract the
28313  ** value. */
28314  {
28315  u64 v64;
28316  u8 n;
28317 
28318  p -= 4;
28319  n = sqlite3GetVarint(p, &v64);
28320  assert( n>5 && n<=9 );
28321  *v = (u32)v64;
28322  return n;
28323  }
28324 #endif
28325 }
28326 
28327 /*
28328 ** Return the number of bytes that will be needed to store the given
28329 ** 64-bit integer.
28330 */
28331 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
28332  int i;
28333  for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
28334  return i;
28335 }
28336 
28337 
28338 /*
28339 ** Read or write a four-byte big-endian integer value.
28340 */
28341 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
28342 #if SQLITE_BYTEORDER==4321
28343  u32 x;
28344  memcpy(&x,p,4);
28345  return x;
28346 #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
28347  && defined(__GNUC__) && GCC_VERSION>=4003000
28348  u32 x;
28349  memcpy(&x,p,4);
28350  return __builtin_bswap32(x);
28351 #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
28352  && defined(_MSC_VER) && _MSC_VER>=1300
28353  u32 x;
28354  memcpy(&x,p,4);
28355  return _byteswap_ulong(x);
28356 #else
28357  testcase( p[0]&0x80 );
28358  return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
28359 #endif
28360 }
28361 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
28362 #if SQLITE_BYTEORDER==4321
28363  memcpy(p,&v,4);
28364 #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
28365  && defined(__GNUC__) && GCC_VERSION>=4003000
28366  u32 x = __builtin_bswap32(v);
28367  memcpy(p,&x,4);
28368 #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
28369  && defined(_MSC_VER) && _MSC_VER>=1300
28370  u32 x = _byteswap_ulong(v);
28371  memcpy(p,&x,4);
28372 #else
28373  p[0] = (u8)(v>>24);
28374  p[1] = (u8)(v>>16);
28375  p[2] = (u8)(v>>8);
28376  p[3] = (u8)v;
28377 #endif
28378 }
28379 
28380 
28381 
28382 /*
28383 ** Translate a single byte of Hex into an integer.
28384 ** This routine only works if h really is a valid hexadecimal
28385 ** character: 0..9a..fA..F
28386 */
28387 SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
28388  assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
28389 #ifdef SQLITE_ASCII
28390  h += 9*(1&(h>>6));
28391 #endif
28392 #ifdef SQLITE_EBCDIC
28393  h += 9*(1&~(h>>4));
28394 #endif
28395  return (u8)(h & 0xf);
28396 }
28397 
28398 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
28399 /*
28400 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
28401 ** value. Return a pointer to its binary value. Space to hold the
28402 ** binary value has been obtained from malloc and must be freed by
28403 ** the calling routine.
28404 */
28405 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
28406  char *zBlob;
28407  int i;
28408 
28409  zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
28410  n--;
28411  if( zBlob ){
28412  for(i=0; i<n; i+=2){
28413  zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
28414  }
28415  zBlob[i/2] = 0;
28416  }
28417  return zBlob;
28418 }
28419 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
28420 
28421 /*
28422 ** Log an error that is an API call on a connection pointer that should
28423 ** not have been used. The "type" of connection pointer is given as the
28424 ** argument. The zType is a word like "NULL" or "closed" or "invalid".
28425 */
28426 static void logBadConnection(const char *zType){
28427  sqlite3_log(SQLITE_MISUSE,
28428  "API call with %s database connection pointer",
28429  zType
28430  );
28431 }
28432 
28433 /*
28434 ** Check to make sure we have a valid db pointer. This test is not
28435 ** foolproof but it does provide some measure of protection against
28436 ** misuse of the interface such as passing in db pointers that are
28437 ** NULL or which have been previously closed. If this routine returns
28438 ** 1 it means that the db pointer is valid and 0 if it should not be
28439 ** dereferenced for any reason. The calling function should invoke
28440 ** SQLITE_MISUSE immediately.
28441 **
28442 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
28443 ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
28444 ** open properly and is not fit for general use but which can be
28445 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
28446 */
28447 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
28448  u32 magic;
28449  if( db==0 ){
28450  logBadConnection("NULL");
28451  return 0;
28452  }
28453  magic = db->magic;
28454  if( magic!=SQLITE_MAGIC_OPEN ){
28455  if( sqlite3SafetyCheckSickOrOk(db) ){
28456  testcase( sqlite3GlobalConfig.xLog!=0 );
28457  logBadConnection("unopened");
28458  }
28459  return 0;
28460  }else{
28461  return 1;
28462  }
28463 }
28464 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
28465  u32 magic;
28466  magic = db->magic;
28467  if( magic!=SQLITE_MAGIC_SICK &&
28468  magic!=SQLITE_MAGIC_OPEN &&
28469  magic!=SQLITE_MAGIC_BUSY ){
28470  testcase( sqlite3GlobalConfig.xLog!=0 );
28471  logBadConnection("invalid");
28472  return 0;
28473  }else{
28474  return 1;
28475  }
28476 }
28477 
28478 /*
28479 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
28480 ** the other 64-bit signed integer at *pA and store the result in *pA.
28481 ** Return 0 on success. Or if the operation would have resulted in an
28482 ** overflow, leave *pA unchanged and return 1.
28483 */
28484 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
28485  i64 iA = *pA;
28486  testcase( iA==0 ); testcase( iA==1 );
28487  testcase( iB==-1 ); testcase( iB==0 );
28488  if( iB>=0 ){
28489  testcase( iA>0 && LARGEST_INT64 - iA == iB );
28490  testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
28491  if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
28492  }else{
28493  testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
28494  testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
28495  if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
28496  }
28497  *pA += iB;
28498  return 0;
28499 }
28500 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
28501  testcase( iB==SMALLEST_INT64+1 );
28502  if( iB==SMALLEST_INT64 ){
28503  testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
28504  if( (*pA)>=0 ) return 1;
28505  *pA -= iB;
28506  return 0;
28507  }else{
28508  return sqlite3AddInt64(pA, -iB);
28509  }
28510 }
28511 #define TWOPOWER32 (((i64)1)<<32)
28512 #define TWOPOWER31 (((i64)1)<<31)
28513 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
28514  i64 iA = *pA;
28515  i64 iA1, iA0, iB1, iB0, r;
28516 
28517  iA1 = iA/TWOPOWER32;
28518  iA0 = iA % TWOPOWER32;
28519  iB1 = iB/TWOPOWER32;
28520  iB0 = iB % TWOPOWER32;
28521  if( iA1==0 ){
28522  if( iB1==0 ){
28523  *pA *= iB;
28524  return 0;
28525  }
28526  r = iA0*iB1;
28527  }else if( iB1==0 ){
28528  r = iA1*iB0;
28529  }else{
28530  /* If both iA1 and iB1 are non-zero, overflow will result */
28531  return 1;
28532  }
28533  testcase( r==(-TWOPOWER31)-1 );
28534  testcase( r==(-TWOPOWER31) );
28535  testcase( r==TWOPOWER31 );
28536  testcase( r==TWOPOWER31-1 );
28537  if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
28538  r *= TWOPOWER32;
28539  if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
28540  *pA = r;
28541  return 0;
28542 }
28543 
28544 /*
28545 ** Compute the absolute value of a 32-bit signed integer, of possible. Or
28546 ** if the integer has a value of -2147483648, return +2147483647
28547 */
28548 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
28549  if( x>=0 ) return x;
28550  if( x==(int)0x80000000 ) return 0x7fffffff;
28551  return -x;
28552 }
28553 
28554 #ifdef SQLITE_ENABLE_8_3_NAMES
28555 /*
28556 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
28557 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
28558 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
28559 ** three characters, then shorten the suffix on z[] to be the last three
28560 ** characters of the original suffix.
28561 **
28562 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
28563 ** do the suffix shortening regardless of URI parameter.
28564 **
28565 ** Examples:
28566 **
28567 ** test.db-journal => test.nal
28568 ** test.db-wal => test.wal
28569 ** test.db-shm => test.shm
28570 ** test.db-mj7f3319fa => test.9fa
28571 */
28572 SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
28573 #if SQLITE_ENABLE_8_3_NAMES<2
28574  if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
28575 #endif
28576  {
28577  int i, sz;
28578  sz = sqlite3Strlen30(z);
28579  for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
28580  if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
28581  }
28582 }
28583 #endif
28584 
28585 /*
28586 ** Find (an approximate) sum of two LogEst values. This computation is
28587 ** not a simple "+" operator because LogEst is stored as a logarithmic
28588 ** value.
28589 **
28590 */
28591 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
28592  static const unsigned char x[] = {
28593  10, 10, /* 0,1 */
28594  9, 9, /* 2,3 */
28595  8, 8, /* 4,5 */
28596  7, 7, 7, /* 6,7,8 */
28597  6, 6, 6, /* 9,10,11 */
28598  5, 5, 5, /* 12-14 */
28599  4, 4, 4, 4, /* 15-18 */
28600  3, 3, 3, 3, 3, 3, /* 19-24 */
28601  2, 2, 2, 2, 2, 2, 2, /* 25-31 */
28602  };
28603  if( a>=b ){
28604  if( a>b+49 ) return a;
28605  if( a>b+31 ) return a+1;
28606  return a+x[a-b];
28607  }else{
28608  if( b>a+49 ) return b;
28609  if( b>a+31 ) return b+1;
28610  return b+x[b-a];
28611  }
28612 }
28613 
28614 /*
28615 ** Convert an integer into a LogEst. In other words, compute an
28616 ** approximation for 10*log2(x).
28617 */
28618 SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
28619  static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
28620  LogEst y = 40;
28621  if( x<8 ){
28622  if( x<2 ) return 0;
28623  while( x<8 ){ y -= 10; x <<= 1; }
28624  }else{
28625  while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/
28626  while( x>15 ){ y += 10; x >>= 1; }
28627  }
28628  return a[x&7] + y - 10;
28629 }
28630 
28631 #ifndef SQLITE_OMIT_VIRTUALTABLE
28632 /*
28633 ** Convert a double into a LogEst
28634 ** In other words, compute an approximation for 10*log2(x).
28635 */
28636 SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
28637  u64 a;
28638  LogEst e;
28639  assert( sizeof(x)==8 && sizeof(a)==8 );
28640  if( x<=1 ) return 0;
28641  if( x<=2000000000 ) return sqlite3LogEst((u64)x);
28642  memcpy(&a, &x, 8);
28643  e = (a>>52) - 1022;
28644  return e*10;
28645 }
28646 #endif /* SQLITE_OMIT_VIRTUALTABLE */
28647 
28648 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
28649  defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
28650  defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
28651 /*
28652 ** Convert a LogEst into an integer.
28653 **
28654 ** Note that this routine is only used when one or more of various
28655 ** non-standard compile-time options is enabled.
28656 */
28657 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
28658  u64 n;
28659  n = x%10;
28660  x /= 10;
28661  if( n>=5 ) n -= 2;
28662  else if( n>=1 ) n -= 1;
28663 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
28664  defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
28665  if( x>60 ) return (u64)LARGEST_INT64;
28666 #else
28667  /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input
28668  ** possible to this routine is 310, resulting in a maximum x of 31 */
28669  assert( x<=60 );
28670 #endif
28671  return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
28672 }
28673 #endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
28674 
28675 /************** End of util.c ************************************************/
28676 /************** Begin file hash.c ********************************************/
28677 /*
28678 ** 2001 September 22
28679 **
28680 ** The author disclaims copyright to this source code. In place of
28681 ** a legal notice, here is a blessing:
28682 **
28683 ** May you do good and not evil.
28684 ** May you find forgiveness for yourself and forgive others.
28685 ** May you share freely, never taking more than you give.
28686 **
28687 *************************************************************************
28688 ** This is the implementation of generic hash-tables
28689 ** used in SQLite.
28690 */
28691 /* #include "sqliteInt.h" */
28692 /* #include <assert.h> */
28693 
28694 /* Turn bulk memory into a hash table object by initializing the
28695 ** fields of the Hash structure.
28696 **
28697 ** "pNew" is a pointer to the hash table that is to be initialized.
28698 */
28699 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
28700  assert( pNew!=0 );
28701  pNew->first = 0;
28702  pNew->count = 0;
28703  pNew->htsize = 0;
28704  pNew->ht = 0;
28705 }
28706 
28707 /* Remove all entries from a hash table. Reclaim all memory.
28708 ** Call this routine to delete a hash table or to reset a hash table
28709 ** to the empty state.
28710 */
28711 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
28712  HashElem *elem; /* For looping over all elements of the table */
28713 
28714  assert( pH!=0 );
28715  elem = pH->first;
28716  pH->first = 0;
28717  sqlite3_free(pH->ht);
28718  pH->ht = 0;
28719  pH->htsize = 0;
28720  while( elem ){
28721  HashElem *next_elem = elem->next;
28722  sqlite3_free(elem);
28723  elem = next_elem;
28724  }
28725  pH->count = 0;
28726 }
28727 
28728 /*
28729 ** The hashing function.
28730 */
28731 static unsigned int strHash(const char *z){
28732  unsigned int h = 0;
28733  unsigned char c;
28734  while( (c = (unsigned char)*z++)!=0 ){ /*OPTIMIZATION-IF-TRUE*/
28735  h = (h<<3) ^ h ^ sqlite3UpperToLower[c];
28736  }
28737  return h;
28738 }
28739 
28740 
28741 /* Link pNew element into the hash table pH. If pEntry!=0 then also
28742 ** insert pNew into the pEntry hash bucket.
28743 */
28744 static void insertElement(
28745  Hash *pH, /* The complete hash table */
28746  struct _ht *pEntry, /* The entry into which pNew is inserted */
28747  HashElem *pNew /* The element to be inserted */
28748 ){
28749  HashElem *pHead; /* First element already in pEntry */
28750  if( pEntry ){
28751  pHead = pEntry->count ? pEntry->chain : 0;
28752  pEntry->count++;
28753  pEntry->chain = pNew;
28754  }else{
28755  pHead = 0;
28756  }
28757  if( pHead ){
28758  pNew->next = pHead;
28759  pNew->prev = pHead->prev;
28760  if( pHead->prev ){ pHead->prev->next = pNew; }
28761  else { pH->first = pNew; }
28762  pHead->prev = pNew;
28763  }else{
28764  pNew->next = pH->first;
28765  if( pH->first ){ pH->first->prev = pNew; }
28766  pNew->prev = 0;
28767  pH->first = pNew;
28768  }
28769 }
28770 
28771 
28772 /* Resize the hash table so that it cantains "new_size" buckets.
28773 **
28774 ** The hash table might fail to resize if sqlite3_malloc() fails or
28775 ** if the new size is the same as the prior size.
28776 ** Return TRUE if the resize occurs and false if not.
28777 */
28778 static int rehash(Hash *pH, unsigned int new_size){
28779  struct _ht *new_ht; /* The new hash table */
28780  HashElem *elem, *next_elem; /* For looping over existing elements */
28781 
28782 #if SQLITE_MALLOC_SOFT_LIMIT>0
28783  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
28784  new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
28785  }
28786  if( new_size==pH->htsize ) return 0;
28787 #endif
28788 
28789  /* The inability to allocates space for a larger hash table is
28790  ** a performance hit but it is not a fatal error. So mark the
28791  ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
28792  ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
28793  ** only zeroes the requested number of bytes whereas this module will
28794  ** use the actual amount of space allocated for the hash table (which
28795  ** may be larger than the requested amount).
28796  */
28797  sqlite3BeginBenignMalloc();
28798  new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
28799  sqlite3EndBenignMalloc();
28800 
28801  if( new_ht==0 ) return 0;
28802  sqlite3_free(pH->ht);
28803  pH->ht = new_ht;
28804  pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
28805  memset(new_ht, 0, new_size*sizeof(struct _ht));
28806  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
28807  unsigned int h = strHash(elem->pKey) % new_size;
28808  next_elem = elem->next;
28809  insertElement(pH, &new_ht[h], elem);
28810  }
28811  return 1;
28812 }
28813 
28814 /* This function (for internal use only) locates an element in an
28815 ** hash table that matches the given key. The hash for this key is
28816 ** also computed and returned in the *pH parameter.
28817 */
28818 static HashElem *findElementWithHash(
28819  const Hash *pH, /* The pH to be searched */
28820  const char *pKey, /* The key we are searching for */
28821  unsigned int *pHash /* Write the hash value here */
28822 ){
28823  HashElem *elem; /* Used to loop thru the element list */
28824  int count; /* Number of elements left to test */
28825  unsigned int h; /* The computed hash */
28826 
28827  if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/
28828  struct _ht *pEntry;
28829  h = strHash(pKey) % pH->htsize;
28830  pEntry = &pH->ht[h];
28831  elem = pEntry->chain;
28832  count = pEntry->count;
28833  }else{
28834  h = 0;
28835  elem = pH->first;
28836  count = pH->count;
28837  }
28838  *pHash = h;
28839  while( count-- ){
28840  assert( elem!=0 );
28841  if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
28842  return elem;
28843  }
28844  elem = elem->next;
28845  }
28846  return 0;
28847 }
28848 
28849 /* Remove a single entry from the hash table given a pointer to that
28850 ** element and a hash on the element's key.
28851 */
28852 static void removeElementGivenHash(
28853  Hash *pH, /* The pH containing "elem" */
28854  HashElem* elem, /* The element to be removed from the pH */
28855  unsigned int h /* Hash value for the element */
28856 ){
28857  struct _ht *pEntry;
28858  if( elem->prev ){
28859  elem->prev->next = elem->next;
28860  }else{
28861  pH->first = elem->next;
28862  }
28863  if( elem->next ){
28864  elem->next->prev = elem->prev;
28865  }
28866  if( pH->ht ){
28867  pEntry = &pH->ht[h];
28868  if( pEntry->chain==elem ){
28869  pEntry->chain = elem->next;
28870  }
28871  pEntry->count--;
28872  assert( pEntry->count>=0 );
28873  }
28874  sqlite3_free( elem );
28875  pH->count--;
28876  if( pH->count==0 ){
28877  assert( pH->first==0 );
28878  assert( pH->count==0 );
28879  sqlite3HashClear(pH);
28880  }
28881 }
28882 
28883 /* Attempt to locate an element of the hash table pH with a key
28884 ** that matches pKey. Return the data for this element if it is
28885 ** found, or NULL if there is no match.
28886 */
28887 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
28888  HashElem *elem; /* The element that matches key */
28889  unsigned int h; /* A hash on key */
28890 
28891  assert( pH!=0 );
28892  assert( pKey!=0 );
28893  elem = findElementWithHash(pH, pKey, &h);
28894  return elem ? elem->data : 0;
28895 }
28896 
28897 /* Insert an element into the hash table pH. The key is pKey
28898 ** and the data is "data".
28899 **
28900 ** If no element exists with a matching key, then a new
28901 ** element is created and NULL is returned.
28902 **
28903 ** If another element already exists with the same key, then the
28904 ** new data replaces the old data and the old data is returned.
28905 ** The key is not copied in this instance. If a malloc fails, then
28906 ** the new data is returned and the hash table is unchanged.
28907 **
28908 ** If the "data" parameter to this function is NULL, then the
28909 ** element corresponding to "key" is removed from the hash table.
28910 */
28911 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
28912  unsigned int h; /* the hash of the key modulo hash table size */
28913  HashElem *elem; /* Used to loop thru the element list */
28914  HashElem *new_elem; /* New element added to the pH */
28915 
28916  assert( pH!=0 );
28917  assert( pKey!=0 );
28918  elem = findElementWithHash(pH,pKey,&h);
28919  if( elem ){
28920  void *old_data = elem->data;
28921  if( data==0 ){
28922  removeElementGivenHash(pH,elem,h);
28923  }else{
28924  elem->data = data;
28925  elem->pKey = pKey;
28926  }
28927  return old_data;
28928  }
28929  if( data==0 ) return 0;
28930  new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
28931  if( new_elem==0 ) return data;
28932  new_elem->pKey = pKey;
28933  new_elem->data = data;
28934  pH->count++;
28935  if( pH->count>=10 && pH->count > 2*pH->htsize ){
28936  if( rehash(pH, pH->count*2) ){
28937  assert( pH->htsize>0 );
28938  h = strHash(pKey) % pH->htsize;
28939  }
28940  }
28941  insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
28942  return 0;
28943 }
28944 
28945 /************** End of hash.c ************************************************/
28946 /************** Begin file opcodes.c *****************************************/
28947 /* Automatically generated. Do not edit */
28948 /* See the tool/mkopcodec.tcl script for details. */
28949 #if !defined(SQLITE_OMIT_EXPLAIN) \
28950  || defined(VDBE_PROFILE) \
28951  || defined(SQLITE_DEBUG)
28952 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
28953 # define OpHelp(X) "\0" X
28954 #else
28955 # define OpHelp(X)
28956 #endif
28957 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
28958  static const char *const azName[] = {
28959  /* 0 */ "Savepoint" OpHelp(""),
28960  /* 1 */ "AutoCommit" OpHelp(""),
28961  /* 2 */ "Transaction" OpHelp(""),
28962  /* 3 */ "SorterNext" OpHelp(""),
28963  /* 4 */ "PrevIfOpen" OpHelp(""),
28964  /* 5 */ "NextIfOpen" OpHelp(""),
28965  /* 6 */ "Prev" OpHelp(""),
28966  /* 7 */ "Next" OpHelp(""),
28967  /* 8 */ "Checkpoint" OpHelp(""),
28968  /* 9 */ "JournalMode" OpHelp(""),
28969  /* 10 */ "Vacuum" OpHelp(""),
28970  /* 11 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
28971  /* 12 */ "VUpdate" OpHelp("data=r[P3@P2]"),
28972  /* 13 */ "Goto" OpHelp(""),
28973  /* 14 */ "Gosub" OpHelp(""),
28974  /* 15 */ "InitCoroutine" OpHelp(""),
28975  /* 16 */ "Yield" OpHelp(""),
28976  /* 17 */ "MustBeInt" OpHelp(""),
28977  /* 18 */ "Jump" OpHelp(""),
28978  /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
28979  /* 20 */ "Once" OpHelp(""),
28980  /* 21 */ "If" OpHelp(""),
28981  /* 22 */ "IfNot" OpHelp(""),
28982  /* 23 */ "SeekLT" OpHelp("key=r[P3@P4]"),
28983  /* 24 */ "SeekLE" OpHelp("key=r[P3@P4]"),
28984  /* 25 */ "SeekGE" OpHelp("key=r[P3@P4]"),
28985  /* 26 */ "SeekGT" OpHelp("key=r[P3@P4]"),
28986  /* 27 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
28987  /* 28 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
28988  /* 29 */ "NoConflict" OpHelp("key=r[P3@P4]"),
28989  /* 30 */ "NotFound" OpHelp("key=r[P3@P4]"),
28990  /* 31 */ "Found" OpHelp("key=r[P3@P4]"),
28991  /* 32 */ "SeekRowid" OpHelp("intkey=r[P3]"),
28992  /* 33 */ "NotExists" OpHelp("intkey=r[P3]"),
28993  /* 34 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
28994  /* 35 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
28995  /* 36 */ "Ne" OpHelp("if r[P1]!=r[P3] goto P2"),
28996  /* 37 */ "Eq" OpHelp("if r[P1]==r[P3] goto P2"),
28997  /* 38 */ "Gt" OpHelp("if r[P1]>r[P3] goto P2"),
28998  /* 39 */ "Le" OpHelp("if r[P1]<=r[P3] goto P2"),
28999  /* 40 */ "Lt" OpHelp("if r[P1]<r[P3] goto P2"),
29000  /* 41 */ "Ge" OpHelp("if r[P1]>=r[P3] goto P2"),
29001  /* 42 */ "Last" OpHelp(""),
29002  /* 43 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
29003  /* 44 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
29004  /* 45 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
29005  /* 46 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
29006  /* 47 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
29007  /* 48 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
29008  /* 49 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
29009  /* 50 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
29010  /* 51 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
29011  /* 52 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
29012  /* 53 */ "SorterSort" OpHelp(""),
29013  /* 54 */ "BitNot" OpHelp("r[P1]= ~r[P1]"),
29014  /* 55 */ "Sort" OpHelp(""),
29015  /* 56 */ "Rewind" OpHelp(""),
29016  /* 57 */ "IdxLE" OpHelp("key=r[P3@P4]"),
29017  /* 58 */ "IdxGT" OpHelp("key=r[P3@P4]"),
29018  /* 59 */ "IdxLT" OpHelp("key=r[P3@P4]"),
29019  /* 60 */ "IdxGE" OpHelp("key=r[P3@P4]"),
29020  /* 61 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
29021  /* 62 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
29022  /* 63 */ "Program" OpHelp(""),
29023  /* 64 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
29024  /* 65 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
29025  /* 66 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]-=P3, goto P2"),
29026  /* 67 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
29027  /* 68 */ "IncrVacuum" OpHelp(""),
29028  /* 69 */ "VNext" OpHelp(""),
29029  /* 70 */ "Init" OpHelp("Start at P2"),
29030  /* 71 */ "Return" OpHelp(""),
29031  /* 72 */ "EndCoroutine" OpHelp(""),
29032  /* 73 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
29033  /* 74 */ "Halt" OpHelp(""),
29034  /* 75 */ "Integer" OpHelp("r[P2]=P1"),
29035  /* 76 */ "Int64" OpHelp("r[P2]=P4"),
29036  /* 77 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
29037  /* 78 */ "Null" OpHelp("r[P2..P3]=NULL"),
29038  /* 79 */ "SoftNull" OpHelp("r[P1]=NULL"),
29039  /* 80 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
29040  /* 81 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
29041  /* 82 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
29042  /* 83 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
29043  /* 84 */ "SCopy" OpHelp("r[P2]=r[P1]"),
29044  /* 85 */ "IntCopy" OpHelp("r[P2]=r[P1]"),
29045  /* 86 */ "ResultRow" OpHelp("output=r[P1@P2]"),
29046  /* 87 */ "CollSeq" OpHelp(""),
29047  /* 88 */ "Function0" OpHelp("r[P3]=func(r[P2@P5])"),
29048  /* 89 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
29049  /* 90 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
29050  /* 91 */ "RealAffinity" OpHelp(""),
29051  /* 92 */ "Cast" OpHelp("affinity(r[P1])"),
29052  /* 93 */ "Permutation" OpHelp(""),
29053  /* 94 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
29054  /* 95 */ "Column" OpHelp("r[P3]=PX"),
29055  /* 96 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
29056  /* 97 */ "String8" OpHelp("r[P2]='P4'"),
29057  /* 98 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
29058  /* 99 */ "Count" OpHelp("r[P2]=count()"),
29059  /* 100 */ "ReadCookie" OpHelp(""),
29060  /* 101 */ "SetCookie" OpHelp(""),
29061  /* 102 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
29062  /* 103 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
29063  /* 104 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
29064  /* 105 */ "OpenAutoindex" OpHelp("nColumn=P2"),
29065  /* 106 */ "OpenEphemeral" OpHelp("nColumn=P2"),
29066  /* 107 */ "SorterOpen" OpHelp(""),
29067  /* 108 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
29068  /* 109 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
29069  /* 110 */ "Close" OpHelp(""),
29070  /* 111 */ "ColumnsUsed" OpHelp(""),
29071  /* 112 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
29072  /* 113 */ "NewRowid" OpHelp("r[P2]=rowid"),
29073  /* 114 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
29074  /* 115 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"),
29075  /* 116 */ "Delete" OpHelp(""),
29076  /* 117 */ "ResetCount" OpHelp(""),
29077  /* 118 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
29078  /* 119 */ "SorterData" OpHelp("r[P2]=data"),
29079  /* 120 */ "RowKey" OpHelp("r[P2]=key"),
29080  /* 121 */ "RowData" OpHelp("r[P2]=data"),
29081  /* 122 */ "Rowid" OpHelp("r[P2]=rowid"),
29082  /* 123 */ "NullRow" OpHelp(""),
29083  /* 124 */ "SorterInsert" OpHelp(""),
29084  /* 125 */ "IdxInsert" OpHelp("key=r[P2]"),
29085  /* 126 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
29086  /* 127 */ "Seek" OpHelp("Move P3 to P1.rowid"),
29087  /* 128 */ "IdxRowid" OpHelp("r[P2]=rowid"),
29088  /* 129 */ "Destroy" OpHelp(""),
29089  /* 130 */ "Clear" OpHelp(""),
29090  /* 131 */ "ResetSorter" OpHelp(""),
29091  /* 132 */ "CreateIndex" OpHelp("r[P2]=root iDb=P1"),
29092  /* 133 */ "Real" OpHelp("r[P2]=P4"),
29093  /* 134 */ "CreateTable" OpHelp("r[P2]=root iDb=P1"),
29094  /* 135 */ "ParseSchema" OpHelp(""),
29095  /* 136 */ "LoadAnalysis" OpHelp(""),
29096  /* 137 */ "DropTable" OpHelp(""),
29097  /* 138 */ "DropIndex" OpHelp(""),
29098  /* 139 */ "DropTrigger" OpHelp(""),
29099  /* 140 */ "IntegrityCk" OpHelp(""),
29100  /* 141 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
29101  /* 142 */ "Param" OpHelp(""),
29102  /* 143 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
29103  /* 144 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
29104  /* 145 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
29105  /* 146 */ "AggStep0" OpHelp("accum=r[P3] step(r[P2@P5])"),
29106  /* 147 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
29107  /* 148 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
29108  /* 149 */ "Expire" OpHelp(""),
29109  /* 150 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
29110  /* 151 */ "VBegin" OpHelp(""),
29111  /* 152 */ "VCreate" OpHelp(""),
29112  /* 153 */ "VDestroy" OpHelp(""),
29113  /* 154 */ "VOpen" OpHelp(""),
29114  /* 155 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
29115  /* 156 */ "VRename" OpHelp(""),
29116  /* 157 */ "Pagecount" OpHelp(""),
29117  /* 158 */ "MaxPgcnt" OpHelp(""),
29118  /* 159 */ "CursorHint" OpHelp(""),
29119  /* 160 */ "Noop" OpHelp(""),
29120  /* 161 */ "Explain" OpHelp(""),
29121  };
29122  return azName[i];
29123 }
29124 #endif
29125 
29126 /************** End of opcodes.c *********************************************/
29127 /************** Begin file os_unix.c *****************************************/
29128 /*
29129 ** 2004 May 22
29130 **
29131 ** The author disclaims copyright to this source code. In place of
29132 ** a legal notice, here is a blessing:
29133 **
29134 ** May you do good and not evil.
29135 ** May you find forgiveness for yourself and forgive others.
29136 ** May you share freely, never taking more than you give.
29137 **
29138 ******************************************************************************
29139 **
29140 ** This file contains the VFS implementation for unix-like operating systems
29141 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
29142 **
29143 ** There are actually several different VFS implementations in this file.
29144 ** The differences are in the way that file locking is done. The default
29145 ** implementation uses Posix Advisory Locks. Alternative implementations
29146 ** use flock(), dot-files, various proprietary locking schemas, or simply
29147 ** skip locking all together.
29148 **
29149 ** This source file is organized into divisions where the logic for various
29150 ** subfunctions is contained within the appropriate division. PLEASE
29151 ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
29152 ** in the correct division and should be clearly labeled.
29153 **
29154 ** The layout of divisions is as follows:
29155 **
29156 ** * General-purpose declarations and utility functions.
29157 ** * Unique file ID logic used by VxWorks.
29158 ** * Various locking primitive implementations (all except proxy locking):
29159 ** + for Posix Advisory Locks
29160 ** + for no-op locks
29161 ** + for dot-file locks
29162 ** + for flock() locking
29163 ** + for named semaphore locks (VxWorks only)
29164 ** + for AFP filesystem locks (MacOSX only)
29165 ** * sqlite3_file methods not associated with locking.
29166 ** * Definitions of sqlite3_io_methods objects for all locking
29167 ** methods plus "finder" functions for each locking method.
29168 ** * sqlite3_vfs method implementations.
29169 ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
29170 ** * Definitions of sqlite3_vfs objects for all locking methods
29171 ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
29172 */
29173 /* #include "sqliteInt.h" */
29174 #if SQLITE_OS_UNIX /* This file is used on unix only */
29175 
29176 /*
29177 ** There are various methods for file locking used for concurrency
29178 ** control:
29179 **
29180 ** 1. POSIX locking (the default),
29181 ** 2. No locking,
29182 ** 3. Dot-file locking,
29183 ** 4. flock() locking,
29184 ** 5. AFP locking (OSX only),
29185 ** 6. Named POSIX semaphores (VXWorks only),
29186 ** 7. proxy locking. (OSX only)
29187 **
29188 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
29189 ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
29190 ** selection of the appropriate locking style based on the filesystem
29191 ** where the database is located.
29192 */
29193 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
29194 # if defined(__APPLE__)
29195 # define SQLITE_ENABLE_LOCKING_STYLE 1
29196 # else
29197 # define SQLITE_ENABLE_LOCKING_STYLE 0
29198 # endif
29199 #endif
29200 
29201 /* Use pread() and pwrite() if they are available */
29202 #if defined(__APPLE__)
29203 # define HAVE_PREAD 1
29204 # define HAVE_PWRITE 1
29205 #endif
29206 #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
29207 # undef USE_PREAD
29208 # define USE_PREAD64 1
29209 #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
29210 # undef USE_PREAD64
29211 # define USE_PREAD 1
29212 #endif
29213 
29214 /*
29215 ** standard include files.
29216 */
29217 #include <sys/types.h>
29218 #include <sys/stat.h>
29219 #include <fcntl.h>
29220 #include <unistd.h>
29221 /* #include <time.h> */
29222 #include <sys/time.h>
29223 #include <errno.h>
29224 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
29225 # include <sys/mman.h>
29226 #endif
29227 
29228 #if SQLITE_ENABLE_LOCKING_STYLE
29229 # include <sys/ioctl.h>
29230 # include <sys/file.h>
29231 # include <sys/param.h>
29232 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
29233 
29234 #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
29235  (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
29236 # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
29237  && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
29238 # define HAVE_GETHOSTUUID 1
29239 # else
29240 # warning "gethostuuid() is disabled."
29241 # endif
29242 #endif
29243 
29244 
29245 #if OS_VXWORKS
29246 /* # include <sys/ioctl.h> */
29247 # include <semaphore.h>
29248 # include <limits.h>
29249 #endif /* OS_VXWORKS */
29250 
29251 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
29252 # include <sys/mount.h>
29253 #endif
29254 
29255 #ifdef HAVE_UTIME
29256 # include <utime.h>
29257 #endif
29258 
29259 /*
29260 ** Allowed values of unixFile.fsFlags
29261 */
29262 #define SQLITE_FSFLAGS_IS_MSDOS 0x1
29263 
29264 /*
29265 ** If we are to be thread-safe, include the pthreads header and define
29266 ** the SQLITE_UNIX_THREADS macro.
29267 */
29268 #if SQLITE_THREADSAFE
29269 /* # include <pthread.h> */
29270 # define SQLITE_UNIX_THREADS 1
29271 #endif
29272 
29273 /*
29274 ** Default permissions when creating a new file
29275 */
29276 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
29277 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
29278 #endif
29279 
29280 /*
29281 ** Default permissions when creating auto proxy dir
29282 */
29283 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
29284 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
29285 #endif
29286 
29287 /*
29288 ** Maximum supported path-length.
29289 */
29290 #define MAX_PATHNAME 512
29291 
29292 /*
29293 ** Maximum supported symbolic links
29294 */
29295 #define SQLITE_MAX_SYMLINKS 100
29296 
29297 /* Always cast the getpid() return type for compatibility with
29298 ** kernel modules in VxWorks. */
29299 #define osGetpid(X) (pid_t)getpid()
29300 
29301 /*
29302 ** Only set the lastErrno if the error code is a real error and not
29303 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
29304 */
29305 #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
29306 
29307 /* Forward references */
29308 typedef struct unixShm unixShm; /* Connection shared memory */
29309 typedef struct unixShmNode unixShmNode; /* Shared memory instance */
29310 typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
29311 typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
29312 
29313 /*
29314 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
29315 ** cannot be closed immediately. In these cases, instances of the following
29316 ** structure are used to store the file descriptor while waiting for an
29317 ** opportunity to either close or reuse it.
29318 */
29319 struct UnixUnusedFd {
29320  int fd; /* File descriptor to close */
29321  int flags; /* Flags this file descriptor was opened with */
29322  UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
29323 };
29324 
29325 /*
29326 ** The unixFile structure is subclass of sqlite3_file specific to the unix
29327 ** VFS implementations.
29328 */
29329 typedef struct unixFile unixFile;
29330 struct unixFile {
29331  sqlite3_io_methods const *pMethod; /* Always the first entry */
29332  sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
29333  unixInodeInfo *pInode; /* Info about locks on this inode */
29334  int h; /* The file descriptor */
29335  unsigned char eFileLock; /* The type of lock held on this fd */
29336  unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
29337  int lastErrno; /* The unix errno from last I/O error */
29338  void *lockingContext; /* Locking style specific state */
29339  UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
29340  const char *zPath; /* Name of the file */
29341  unixShm *pShm; /* Shared memory segment information */
29342  int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
29343 #if SQLITE_MAX_MMAP_SIZE>0
29344  int nFetchOut; /* Number of outstanding xFetch refs */
29345  sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
29346  sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
29347  sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
29348  void *pMapRegion; /* Memory mapped region */
29349 #endif
29350 #ifdef __QNXNTO__
29351  int sectorSize; /* Device sector size */
29352  int deviceCharacteristics; /* Precomputed device characteristics */
29353 #endif
29354 #if SQLITE_ENABLE_LOCKING_STYLE
29355  int openFlags; /* The flags specified at open() */
29356 #endif
29357 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
29358  unsigned fsFlags; /* cached details from statfs() */
29359 #endif
29360 #if OS_VXWORKS
29361  struct vxworksFileId *pId; /* Unique file ID */
29362 #endif
29363 #ifdef SQLITE_DEBUG
29364  /* The next group of variables are used to track whether or not the
29365  ** transaction counter in bytes 24-27 of database files are updated
29366  ** whenever any part of the database changes. An assertion fault will
29367  ** occur if a file is updated without also updating the transaction
29368  ** counter. This test is made to avoid new problems similar to the
29369  ** one described by ticket #3584.
29370  */
29371  unsigned char transCntrChng; /* True if the transaction counter changed */
29372  unsigned char dbUpdate; /* True if any part of database file changed */
29373  unsigned char inNormalWrite; /* True if in a normal write operation */
29374 
29375 #endif
29376 
29377 #ifdef SQLITE_TEST
29378  /* In test mode, increase the size of this structure a bit so that
29379  ** it is larger than the struct CrashFile defined in test6.c.
29380  */
29381  char aPadding[32];
29382 #endif
29383 };
29384 
29385 /* This variable holds the process id (pid) from when the xRandomness()
29386 ** method was called. If xOpen() is called from a different process id,
29387 ** indicating that a fork() has occurred, the PRNG will be reset.
29388 */
29389 static pid_t randomnessPid = 0;
29390 
29391 /*
29392 ** Allowed values for the unixFile.ctrlFlags bitmask:
29393 */
29394 #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
29395 #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
29396 #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
29397 #ifndef SQLITE_DISABLE_DIRSYNC
29398 # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
29399 #else
29400 # define UNIXFILE_DIRSYNC 0x00
29401 #endif
29402 #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
29403 #define UNIXFILE_DELETE 0x20 /* Delete on close */
29404 #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
29405 #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
29406 
29407 /*
29408 ** Include code that is common to all os_*.c files
29409 */
29410 /************** Include os_common.h in the middle of os_unix.c ***************/
29411 /************** Begin file os_common.h ***************************************/
29412 /*
29413 ** 2004 May 22
29414 **
29415 ** The author disclaims copyright to this source code. In place of
29416 ** a legal notice, here is a blessing:
29417 **
29418 ** May you do good and not evil.
29419 ** May you find forgiveness for yourself and forgive others.
29420 ** May you share freely, never taking more than you give.
29421 **
29422 ******************************************************************************
29423 **
29424 ** This file contains macros and a little bit of code that is common to
29425 ** all of the platform-specific files (os_*.c) and is #included into those
29426 ** files.
29427 **
29428 ** This file should be #included by the os_*.c files only. It is not a
29429 ** general purpose header file.
29430 */
29431 #ifndef _OS_COMMON_H_
29432 #define _OS_COMMON_H_
29433 
29434 /*
29435 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
29436 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
29437 ** switch. The following code should catch this problem at compile-time.
29438 */
29439 #ifdef MEMORY_DEBUG
29440 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
29441 #endif
29442 
29443 /*
29444 ** Macros for performance tracing. Normally turned off. Only works
29445 ** on i486 hardware.
29446 */
29447 #ifdef SQLITE_PERFORMANCE_TRACE
29448 
29449 /*
29450 ** hwtime.h contains inline assembler code for implementing
29451 ** high-performance timing routines.
29452 */
29453 /************** Include hwtime.h in the middle of os_common.h ****************/
29454 /************** Begin file hwtime.h ******************************************/
29455 /*
29456 ** 2008 May 27
29457 **
29458 ** The author disclaims copyright to this source code. In place of
29459 ** a legal notice, here is a blessing:
29460 **
29461 ** May you do good and not evil.
29462 ** May you find forgiveness for yourself and forgive others.
29463 ** May you share freely, never taking more than you give.
29464 **
29465 ******************************************************************************
29466 **
29467 ** This file contains inline asm code for retrieving "high-performance"
29468 ** counters for x86 class CPUs.
29469 */
29470 #ifndef SQLITE_HWTIME_H
29471 #define SQLITE_HWTIME_H
29472 
29473 /*
29474 ** The following routine only works on pentium-class (or newer) processors.
29475 ** It uses the RDTSC opcode to read the cycle count value out of the
29476 ** processor and returns that value. This can be used for high-res
29477 ** profiling.
29478 */
29479 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
29480  (defined(i386) || defined(__i386__) || defined(_M_IX86))
29481 
29482  #if defined(__GNUC__)
29483 
29484  __inline__ sqlite_uint64 sqlite3Hwtime(void){
29485  unsigned int lo, hi;
29486  __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
29487  return (sqlite_uint64)hi << 32 | lo;
29488  }
29489 
29490  #elif defined(_MSC_VER)
29491 
29492  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
29493  __asm {
29494  rdtsc
29495  ret ; return value at EDX:EAX
29496  }
29497  }
29498 
29499  #endif
29500 
29501 #elif (defined(__GNUC__) && defined(__x86_64__))
29502 
29503  __inline__ sqlite_uint64 sqlite3Hwtime(void){
29504  unsigned long val;
29505  __asm__ __volatile__ ("rdtsc" : "=A" (val));
29506  return val;
29507  }
29508 
29509 #elif (defined(__GNUC__) && defined(__ppc__))
29510 
29511  __inline__ sqlite_uint64 sqlite3Hwtime(void){
29512  unsigned long long retval;
29513  unsigned long junk;
29514  __asm__ __volatile__ ("\n\
29515  1: mftbu %1\n\
29516  mftb %L0\n\
29517  mftbu %0\n\
29518  cmpw %0,%1\n\
29519  bne 1b"
29520  : "=r" (retval), "=r" (junk));
29521  return retval;
29522  }
29523 
29524 #else
29525 
29526  #error Need implementation of sqlite3Hwtime() for your platform.
29527 
29528  /*
29529  ** To compile without implementing sqlite3Hwtime() for your platform,
29530  ** you can remove the above #error and use the following
29531  ** stub function. You will lose timing support for many
29532  ** of the debugging and testing utilities, but it should at
29533  ** least compile and run.
29534  */
29535 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
29536 
29537 #endif
29538 
29539 #endif /* !defined(SQLITE_HWTIME_H) */
29540 
29541 /************** End of hwtime.h **********************************************/
29542 /************** Continuing where we left off in os_common.h ******************/
29543 
29544 static sqlite_uint64 g_start;
29545 static sqlite_uint64 g_elapsed;
29546 #define TIMER_START g_start=sqlite3Hwtime()
29547 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
29548 #define TIMER_ELAPSED g_elapsed
29549 #else
29550 #define TIMER_START
29551 #define TIMER_END
29552 #define TIMER_ELAPSED ((sqlite_uint64)0)
29553 #endif
29554 
29555 /*
29556 ** If we compile with the SQLITE_TEST macro set, then the following block
29557 ** of code will give us the ability to simulate a disk I/O error. This
29558 ** is used for testing the I/O recovery logic.
29559 */
29560 #if defined(SQLITE_TEST)
29561 SQLITE_API extern int sqlite3_io_error_hit;
29562 SQLITE_API extern int sqlite3_io_error_hardhit;
29563 SQLITE_API extern int sqlite3_io_error_pending;
29564 SQLITE_API extern int sqlite3_io_error_persist;
29565 SQLITE_API extern int sqlite3_io_error_benign;
29566 SQLITE_API extern int sqlite3_diskfull_pending;
29567 SQLITE_API extern int sqlite3_diskfull;
29568 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
29569 #define SimulateIOError(CODE) \
29570  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
29571  || sqlite3_io_error_pending-- == 1 ) \
29572  { local_ioerr(); CODE; }
29573 static void local_ioerr(){
29574  IOTRACE(("IOERR\n"));
29575  sqlite3_io_error_hit++;
29576  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
29577 }
29578 #define SimulateDiskfullError(CODE) \
29579  if( sqlite3_diskfull_pending ){ \
29580  if( sqlite3_diskfull_pending == 1 ){ \
29581  local_ioerr(); \
29582  sqlite3_diskfull = 1; \
29583  sqlite3_io_error_hit = 1; \
29584  CODE; \
29585  }else{ \
29586  sqlite3_diskfull_pending--; \
29587  } \
29588  }
29589 #else
29590 #define SimulateIOErrorBenign(X)
29591 #define SimulateIOError(A)
29592 #define SimulateDiskfullError(A)
29593 #endif /* defined(SQLITE_TEST) */
29594 
29595 /*
29596 ** When testing, keep a count of the number of open files.
29597 */
29598 #if defined(SQLITE_TEST)
29599 SQLITE_API extern int sqlite3_open_file_count;
29600 #define OpenCounter(X) sqlite3_open_file_count+=(X)
29601 #else
29602 #define OpenCounter(X)
29603 #endif /* defined(SQLITE_TEST) */
29604 
29605 #endif /* !defined(_OS_COMMON_H_) */
29606 
29607 /************** End of os_common.h *******************************************/
29608 /************** Continuing where we left off in os_unix.c ********************/
29609 
29610 /*
29611 ** Define various macros that are missing from some systems.
29612 */
29613 #ifndef O_LARGEFILE
29614 # define O_LARGEFILE 0
29615 #endif
29616 #ifdef SQLITE_DISABLE_LFS
29617 # undef O_LARGEFILE
29618 # define O_LARGEFILE 0
29619 #endif
29620 #ifndef O_NOFOLLOW
29621 # define O_NOFOLLOW 0
29622 #endif
29623 #ifndef O_BINARY
29624 # define O_BINARY 0
29625 #endif
29626 
29627 /*
29628 ** The threadid macro resolves to the thread-id or to 0. Used for
29629 ** testing and debugging only.
29630 */
29631 #if SQLITE_THREADSAFE
29632 #define threadid pthread_self()
29633 #else
29634 #define threadid 0
29635 #endif
29636 
29637 /*
29638 ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
29639 */
29640 #if !defined(HAVE_MREMAP)
29641 # if defined(__linux__) && defined(_GNU_SOURCE)
29642 # define HAVE_MREMAP 1
29643 # else
29644 # define HAVE_MREMAP 0
29645 # endif
29646 #endif
29647 
29648 /*
29649 ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
29650 ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
29651 */
29652 #ifdef __ANDROID__
29653 # define lseek lseek64
29654 #endif
29655 
29656 /*
29657 ** Different Unix systems declare open() in different ways. Same use
29658 ** open(const char*,int,mode_t). Others use open(const char*,int,...).
29659 ** The difference is important when using a pointer to the function.
29660 **
29661 ** The safest way to deal with the problem is to always use this wrapper
29662 ** which always has the same well-defined interface.
29663 */
29664 static int posixOpen(const char *zFile, int flags, int mode){
29665  return open(zFile, flags, mode);
29666 }
29667 
29668 /* Forward reference */
29669 static int openDirectory(const char*, int*);
29670 static int unixGetpagesize(void);
29671 
29672 /*
29673 ** Many system calls are accessed through pointer-to-functions so that
29674 ** they may be overridden at runtime to facilitate fault injection during
29675 ** testing and sandboxing. The following array holds the names and pointers
29676 ** to all overrideable system calls.
29677 */
29678 static struct unix_syscall {
29679  const char *zName; /* Name of the system call */
29680  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
29681  sqlite3_syscall_ptr pDefault; /* Default value */
29682 } aSyscall[] = {
29683  { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
29684 #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
29685 
29686  { "close", (sqlite3_syscall_ptr)close, 0 },
29687 #define osClose ((int(*)(int))aSyscall[1].pCurrent)
29688 
29689  { "access", (sqlite3_syscall_ptr)access, 0 },
29690 #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
29691 
29692  { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
29693 #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
29694 
29695  { "stat", (sqlite3_syscall_ptr)stat, 0 },
29696 #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
29697 
29698 /*
29699 ** The DJGPP compiler environment looks mostly like Unix, but it
29700 ** lacks the fcntl() system call. So redefine fcntl() to be something
29701 ** that always succeeds. This means that locking does not occur under
29702 ** DJGPP. But it is DOS - what did you expect?
29703 */
29704 #ifdef __DJGPP__
29705  { "fstat", 0, 0 },
29706 #define osFstat(a,b,c) 0
29707 #else
29708  { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
29709 #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
29710 #endif
29711 
29712  { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
29713 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
29714 
29715  { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
29716 #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
29717 
29718  { "read", (sqlite3_syscall_ptr)read, 0 },
29719 #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
29720 
29721 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
29722  { "pread", (sqlite3_syscall_ptr)pread, 0 },
29723 #else
29724  { "pread", (sqlite3_syscall_ptr)0, 0 },
29725 #endif
29726 #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
29727 
29728 #if defined(USE_PREAD64)
29729  { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
29730 #else
29731  { "pread64", (sqlite3_syscall_ptr)0, 0 },
29732 #endif
29733 #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
29734 
29735  { "write", (sqlite3_syscall_ptr)write, 0 },
29736 #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
29737 
29738 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
29739  { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
29740 #else
29741  { "pwrite", (sqlite3_syscall_ptr)0, 0 },
29742 #endif
29743 #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
29744  aSyscall[12].pCurrent)
29745 
29746 #if defined(USE_PREAD64)
29747  { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
29748 #else
29749  { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
29750 #endif
29751 #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
29752  aSyscall[13].pCurrent)
29753 
29754  { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
29755 #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
29756 
29757 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
29758  { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
29759 #else
29760  { "fallocate", (sqlite3_syscall_ptr)0, 0 },
29761 #endif
29762 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
29763 
29764  { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
29765 #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
29766 
29767  { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
29768 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
29769 
29770  { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
29771 #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
29772 
29773  { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
29774 #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
29775 
29776 #if defined(HAVE_FCHOWN)
29777  { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
29778 #else
29779  { "fchown", (sqlite3_syscall_ptr)0, 0 },
29780 #endif
29781 #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
29782 
29783  { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
29784 #define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
29785 
29786 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
29787  { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
29788 #else
29789  { "mmap", (sqlite3_syscall_ptr)0, 0 },
29790 #endif
29791 #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
29792 
29793 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
29794  { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
29795 #else
29796  { "munmap", (sqlite3_syscall_ptr)0, 0 },
29797 #endif
29798 #define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
29799 
29800 #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
29801  { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
29802 #else
29803  { "mremap", (sqlite3_syscall_ptr)0, 0 },
29804 #endif
29805 #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
29806 
29807 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
29808  { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
29809 #else
29810  { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
29811 #endif
29812 #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
29813 
29814 #if defined(HAVE_READLINK)
29815  { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
29816 #else
29817  { "readlink", (sqlite3_syscall_ptr)0, 0 },
29818 #endif
29819 #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
29820 
29821 #if defined(HAVE_LSTAT)
29822  { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
29823 #else
29824  { "lstat", (sqlite3_syscall_ptr)0, 0 },
29825 #endif
29826 #define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
29827 
29828 }; /* End of the overrideable system calls */
29829 
29830 
29831 /*
29832 ** On some systems, calls to fchown() will trigger a message in a security
29833 ** log if they come from non-root processes. So avoid calling fchown() if
29834 ** we are not running as root.
29835 */
29836 static int robustFchown(int fd, uid_t uid, gid_t gid){
29837 #if defined(HAVE_FCHOWN)
29838  return osGeteuid() ? 0 : osFchown(fd,uid,gid);
29839 #else
29840  return 0;
29841 #endif
29842 }
29843 
29844 /*
29845 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
29846 ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
29847 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
29848 ** system call named zName.
29849 */
29850 static int unixSetSystemCall(
29851  sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
29852  const char *zName, /* Name of system call to override */
29853  sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
29854 ){
29855  unsigned int i;
29856  int rc = SQLITE_NOTFOUND;
29857 
29858  UNUSED_PARAMETER(pNotUsed);
29859  if( zName==0 ){
29860  /* If no zName is given, restore all system calls to their default
29861  ** settings and return NULL
29862  */
29863  rc = SQLITE_OK;
29864  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
29865  if( aSyscall[i].pDefault ){
29866  aSyscall[i].pCurrent = aSyscall[i].pDefault;
29867  }
29868  }
29869  }else{
29870  /* If zName is specified, operate on only the one system call
29871  ** specified.
29872  */
29873  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
29874  if( strcmp(zName, aSyscall[i].zName)==0 ){
29875  if( aSyscall[i].pDefault==0 ){
29876  aSyscall[i].pDefault = aSyscall[i].pCurrent;
29877  }
29878  rc = SQLITE_OK;
29879  if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
29880  aSyscall[i].pCurrent = pNewFunc;
29881  break;
29882  }
29883  }
29884  }
29885  return rc;
29886 }
29887 
29888 /*
29889 ** Return the value of a system call. Return NULL if zName is not a
29890 ** recognized system call name. NULL is also returned if the system call
29891 ** is currently undefined.
29892 */
29893 static sqlite3_syscall_ptr unixGetSystemCall(
29894  sqlite3_vfs *pNotUsed,
29895  const char *zName
29896 ){
29897  unsigned int i;
29898 
29899  UNUSED_PARAMETER(pNotUsed);
29900  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
29901  if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
29902  }
29903  return 0;
29904 }
29905 
29906 /*
29907 ** Return the name of the first system call after zName. If zName==NULL
29908 ** then return the name of the first system call. Return NULL if zName
29909 ** is the last system call or if zName is not the name of a valid
29910 ** system call.
29911 */
29912 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
29913  int i = -1;
29914 
29915  UNUSED_PARAMETER(p);
29916  if( zName ){
29917  for(i=0; i<ArraySize(aSyscall)-1; i++){
29918  if( strcmp(zName, aSyscall[i].zName)==0 ) break;
29919  }
29920  }
29921  for(i++; i<ArraySize(aSyscall); i++){
29922  if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
29923  }
29924  return 0;
29925 }
29926 
29927 /*
29928 ** Do not accept any file descriptor less than this value, in order to avoid
29929 ** opening database file using file descriptors that are commonly used for
29930 ** standard input, output, and error.
29931 */
29932 #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
29933 # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
29934 #endif
29935 
29936 /*
29937 ** Invoke open(). Do so multiple times, until it either succeeds or
29938 ** fails for some reason other than EINTR.
29939 **
29940 ** If the file creation mode "m" is 0 then set it to the default for
29941 ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
29942 ** 0644) as modified by the system umask. If m is not 0, then
29943 ** make the file creation mode be exactly m ignoring the umask.
29944 **
29945 ** The m parameter will be non-zero only when creating -wal, -journal,
29946 ** and -shm files. We want those files to have *exactly* the same
29947 ** permissions as their original database, unadulterated by the umask.
29948 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
29949 ** transaction crashes and leaves behind hot journals, then any
29950 ** process that is able to write to the database will also be able to
29951 ** recover the hot journals.
29952 */
29953 static int robust_open(const char *z, int f, mode_t m){
29954  int fd;
29955  mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
29956  while(1){
29957 #if defined(O_CLOEXEC)
29958  fd = osOpen(z,f|O_CLOEXEC,m2);
29959 #else
29960  fd = osOpen(z,f,m2);
29961 #endif
29962  if( fd<0 ){
29963  if( errno==EINTR ) continue;
29964  break;
29965  }
29966  if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
29967  osClose(fd);
29968  sqlite3_log(SQLITE_WARNING,
29969  "attempt to open \"%s\" as file descriptor %d", z, fd);
29970  fd = -1;
29971  if( osOpen("/dev/null", f, m)<0 ) break;
29972  }
29973  if( fd>=0 ){
29974  if( m!=0 ){
29975  struct stat statbuf;
29976  if( osFstat(fd, &statbuf)==0
29977  && statbuf.st_size==0
29978  && (statbuf.st_mode&0777)!=m
29979  ){
29980  osFchmod(fd, m);
29981  }
29982  }
29983 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
29984  osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
29985 #endif
29986  }
29987  return fd;
29988 }
29989 
29990 /*
29991 ** Helper functions to obtain and relinquish the global mutex. The
29992 ** global mutex is used to protect the unixInodeInfo and
29993 ** vxworksFileId objects used by this file, all of which may be
29994 ** shared by multiple threads.
29995 **
29996 ** Function unixMutexHeld() is used to assert() that the global mutex
29997 ** is held when required. This function is only used as part of assert()
29998 ** statements. e.g.
29999 **
30000 ** unixEnterMutex()
30001 ** assert( unixMutexHeld() );
30002 ** unixEnterLeave()
30003 */
30004 static void unixEnterMutex(void){
30005  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
30006 }
30007 static void unixLeaveMutex(void){
30008  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
30009 }
30010 #ifdef SQLITE_DEBUG
30011 static int unixMutexHeld(void) {
30012  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
30013 }
30014 #endif
30015 
30016 
30017 #ifdef SQLITE_HAVE_OS_TRACE
30018 /*
30019 ** Helper function for printing out trace information from debugging
30020 ** binaries. This returns the string representation of the supplied
30021 ** integer lock-type.
30022 */
30023 static const char *azFileLock(int eFileLock){
30024  switch( eFileLock ){
30025  case NO_LOCK: return "NONE";
30026  case SHARED_LOCK: return "SHARED";
30027  case RESERVED_LOCK: return "RESERVED";
30028  case PENDING_LOCK: return "PENDING";
30029  case EXCLUSIVE_LOCK: return "EXCLUSIVE";
30030  }
30031  return "ERROR";
30032 }
30033 #endif
30034 
30035 #ifdef SQLITE_LOCK_TRACE
30036 /*
30037 ** Print out information about all locking operations.
30038 **
30039 ** This routine is used for troubleshooting locks on multithreaded
30040 ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
30041 ** command-line option on the compiler. This code is normally
30042 ** turned off.
30043 */
30044 static int lockTrace(int fd, int op, struct flock *p){
30045  char *zOpName, *zType;
30046  int s;
30047  int savedErrno;
30048  if( op==F_GETLK ){
30049  zOpName = "GETLK";
30050  }else if( op==F_SETLK ){
30051  zOpName = "SETLK";
30052  }else{
30053  s = osFcntl(fd, op, p);
30054  sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
30055  return s;
30056  }
30057  if( p->l_type==F_RDLCK ){
30058  zType = "RDLCK";
30059  }else if( p->l_type==F_WRLCK ){
30060  zType = "WRLCK";
30061  }else if( p->l_type==F_UNLCK ){
30062  zType = "UNLCK";
30063  }else{
30064  assert( 0 );
30065  }
30066  assert( p->l_whence==SEEK_SET );
30067  s = osFcntl(fd, op, p);
30068  savedErrno = errno;
30069  sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
30070  threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
30071  (int)p->l_pid, s);
30072  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
30073  struct flock l2;
30074  l2 = *p;
30075  osFcntl(fd, F_GETLK, &l2);
30076  if( l2.l_type==F_RDLCK ){
30077  zType = "RDLCK";
30078  }else if( l2.l_type==F_WRLCK ){
30079  zType = "WRLCK";
30080  }else if( l2.l_type==F_UNLCK ){
30081  zType = "UNLCK";
30082  }else{
30083  assert( 0 );
30084  }
30085  sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
30086  zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
30087  }
30088  errno = savedErrno;
30089  return s;
30090 }
30091 #undef osFcntl
30092 #define osFcntl lockTrace
30093 #endif /* SQLITE_LOCK_TRACE */
30094 
30095 /*
30096 ** Retry ftruncate() calls that fail due to EINTR
30097 **
30098 ** All calls to ftruncate() within this file should be made through
30099 ** this wrapper. On the Android platform, bypassing the logic below
30100 ** could lead to a corrupt database.
30101 */
30102 static int robust_ftruncate(int h, sqlite3_int64 sz){
30103  int rc;
30104 #ifdef __ANDROID__
30105  /* On Android, ftruncate() always uses 32-bit offsets, even if
30106  ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
30107  ** truncate a file to any size larger than 2GiB. Silently ignore any
30108  ** such attempts. */
30109  if( sz>(sqlite3_int64)0x7FFFFFFF ){
30110  rc = SQLITE_OK;
30111  }else
30112 #endif
30113  do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
30114  return rc;
30115 }
30116 
30117 /*
30118 ** This routine translates a standard POSIX errno code into something
30119 ** useful to the clients of the sqlite3 functions. Specifically, it is
30120 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
30121 ** and a variety of "please close the file descriptor NOW" errors into
30122 ** SQLITE_IOERR
30123 **
30124 ** Errors during initialization of locks, or file system support for locks,
30125 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
30126 */
30127 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
30128  assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
30129  (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
30130  (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
30131  (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
30132  switch (posixError) {
30133  case EACCES:
30134  case EAGAIN:
30135  case ETIMEDOUT:
30136  case EBUSY:
30137  case EINTR:
30138  case ENOLCK:
30139  /* random NFS retry error, unless during file system support
30140  * introspection, in which it actually means what it says */
30141  return SQLITE_BUSY;
30142 
30143  case EPERM:
30144  return SQLITE_PERM;
30145 
30146  default:
30147  return sqliteIOErr;
30148  }
30149 }
30150 
30151 
30152 /******************************************************************************
30153 ****************** Begin Unique File ID Utility Used By VxWorks ***************
30154 **
30155 ** On most versions of unix, we can get a unique ID for a file by concatenating
30156 ** the device number and the inode number. But this does not work on VxWorks.
30157 ** On VxWorks, a unique file id must be based on the canonical filename.
30158 **
30159 ** A pointer to an instance of the following structure can be used as a
30160 ** unique file ID in VxWorks. Each instance of this structure contains
30161 ** a copy of the canonical filename. There is also a reference count.
30162 ** The structure is reclaimed when the number of pointers to it drops to
30163 ** zero.
30164 **
30165 ** There are never very many files open at one time and lookups are not
30166 ** a performance-critical path, so it is sufficient to put these
30167 ** structures on a linked list.
30168 */
30170  struct vxworksFileId *pNext; /* Next in a list of them all */
30171  int nRef; /* Number of references to this one */
30172  int nName; /* Length of the zCanonicalName[] string */
30173  char *zCanonicalName; /* Canonical filename */
30174 };
30175 
30176 #if OS_VXWORKS
30177 /*
30178 ** All unique filenames are held on a linked list headed by this
30179 ** variable:
30180 */
30181 static struct vxworksFileId *vxworksFileList = 0;
30182 
30183 /*
30184 ** Simplify a filename into its canonical form
30185 ** by making the following changes:
30186 **
30187 ** * removing any trailing and duplicate /
30188 ** * convert /./ into just /
30189 ** * convert /A/../ where A is any simple name into just /
30190 **
30191 ** Changes are made in-place. Return the new name length.
30192 **
30193 ** The original filename is in z[0..n-1]. Return the number of
30194 ** characters in the simplified name.
30195 */
30196 static int vxworksSimplifyName(char *z, int n){
30197  int i, j;
30198  while( n>1 && z[n-1]=='/' ){ n--; }
30199  for(i=j=0; i<n; i++){
30200  if( z[i]=='/' ){
30201  if( z[i+1]=='/' ) continue;
30202  if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
30203  i += 1;
30204  continue;
30205  }
30206  if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
30207  while( j>0 && z[j-1]!='/' ){ j--; }
30208  if( j>0 ){ j--; }
30209  i += 2;
30210  continue;
30211  }
30212  }
30213  z[j++] = z[i];
30214  }
30215  z[j] = 0;
30216  return j;
30217 }
30218 
30219 /*
30220 ** Find a unique file ID for the given absolute pathname. Return
30221 ** a pointer to the vxworksFileId object. This pointer is the unique
30222 ** file ID.
30223 **
30224 ** The nRef field of the vxworksFileId object is incremented before
30225 ** the object is returned. A new vxworksFileId object is created
30226 ** and added to the global list if necessary.
30227 **
30228 ** If a memory allocation error occurs, return NULL.
30229 */
30230 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
30231  struct vxworksFileId *pNew; /* search key and new file ID */
30232  struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
30233  int n; /* Length of zAbsoluteName string */
30234 
30235  assert( zAbsoluteName[0]=='/' );
30236  n = (int)strlen(zAbsoluteName);
30237  pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
30238  if( pNew==0 ) return 0;
30239  pNew->zCanonicalName = (char*)&pNew[1];
30240  memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
30241  n = vxworksSimplifyName(pNew->zCanonicalName, n);
30242 
30243  /* Search for an existing entry that matching the canonical name.
30244  ** If found, increment the reference count and return a pointer to
30245  ** the existing file ID.
30246  */
30247  unixEnterMutex();
30248  for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
30249  if( pCandidate->nName==n
30250  && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
30251  ){
30252  sqlite3_free(pNew);
30253  pCandidate->nRef++;
30254  unixLeaveMutex();
30255  return pCandidate;
30256  }
30257  }
30258 
30259  /* No match was found. We will make a new file ID */
30260  pNew->nRef = 1;
30261  pNew->nName = n;
30262  pNew->pNext = vxworksFileList;
30263  vxworksFileList = pNew;
30264  unixLeaveMutex();
30265  return pNew;
30266 }
30267 
30268 /*
30269 ** Decrement the reference count on a vxworksFileId object. Free
30270 ** the object when the reference count reaches zero.
30271 */
30272 static void vxworksReleaseFileId(struct vxworksFileId *pId){
30273  unixEnterMutex();
30274  assert( pId->nRef>0 );
30275  pId->nRef--;
30276  if( pId->nRef==0 ){
30277  struct vxworksFileId **pp;
30278  for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
30279  assert( *pp==pId );
30280  *pp = pId->pNext;
30281  sqlite3_free(pId);
30282  }
30283  unixLeaveMutex();
30284 }
30285 #endif /* OS_VXWORKS */
30286 /*************** End of Unique File ID Utility Used By VxWorks ****************
30287 ******************************************************************************/
30288 
30289 
30290 /******************************************************************************
30291 *************************** Posix Advisory Locking ****************************
30292 **
30293 ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
30294 ** section 6.5.2.2 lines 483 through 490 specify that when a process
30295 ** sets or clears a lock, that operation overrides any prior locks set
30296 ** by the same process. It does not explicitly say so, but this implies
30297 ** that it overrides locks set by the same process using a different
30298 ** file descriptor. Consider this test case:
30299 **
30300 ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
30301 ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
30302 **
30303 ** Suppose ./file1 and ./file2 are really the same file (because
30304 ** one is a hard or symbolic link to the other) then if you set
30305 ** an exclusive lock on fd1, then try to get an exclusive lock
30306 ** on fd2, it works. I would have expected the second lock to
30307 ** fail since there was already a lock on the file due to fd1.
30308 ** But not so. Since both locks came from the same process, the
30309 ** second overrides the first, even though they were on different
30310 ** file descriptors opened on different file names.
30311 **
30312 ** This means that we cannot use POSIX locks to synchronize file access
30313 ** among competing threads of the same process. POSIX locks will work fine
30314 ** to synchronize access for threads in separate processes, but not
30315 ** threads within the same process.
30316 **
30317 ** To work around the problem, SQLite has to manage file locks internally
30318 ** on its own. Whenever a new database is opened, we have to find the
30319 ** specific inode of the database file (the inode is determined by the
30320 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
30321 ** and check for locks already existing on that inode. When locks are
30322 ** created or removed, we have to look at our own internal record of the
30323 ** locks to see if another thread has previously set a lock on that same
30324 ** inode.
30325 **
30326 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
30327 ** For VxWorks, we have to use the alternative unique ID system based on
30328 ** canonical filename and implemented in the previous division.)
30329 **
30330 ** The sqlite3_file structure for POSIX is no longer just an integer file
30331 ** descriptor. It is now a structure that holds the integer file
30332 ** descriptor and a pointer to a structure that describes the internal
30333 ** locks on the corresponding inode. There is one locking structure
30334 ** per inode, so if the same inode is opened twice, both unixFile structures
30335 ** point to the same locking structure. The locking structure keeps
30336 ** a reference count (so we will know when to delete it) and a "cnt"
30337 ** field that tells us its internal lock status. cnt==0 means the
30338 ** file is unlocked. cnt==-1 means the file has an exclusive lock.
30339 ** cnt>0 means there are cnt shared locks on the file.
30340 **
30341 ** Any attempt to lock or unlock a file first checks the locking
30342 ** structure. The fcntl() system call is only invoked to set a
30343 ** POSIX lock if the internal lock structure transitions between
30344 ** a locked and an unlocked state.
30345 **
30346 ** But wait: there are yet more problems with POSIX advisory locks.
30347 **
30348 ** If you close a file descriptor that points to a file that has locks,
30349 ** all locks on that file that are owned by the current process are
30350 ** released. To work around this problem, each unixInodeInfo object
30351 ** maintains a count of the number of pending locks on tha inode.
30352 ** When an attempt is made to close an unixFile, if there are
30353 ** other unixFile open on the same inode that are holding locks, the call
30354 ** to close() the file descriptor is deferred until all of the locks clear.
30355 ** The unixInodeInfo structure keeps a list of file descriptors that need to
30356 ** be closed and that list is walked (and cleared) when the last lock
30357 ** clears.
30358 **
30359 ** Yet another problem: LinuxThreads do not play well with posix locks.
30360 **
30361 ** Many older versions of linux use the LinuxThreads library which is
30362 ** not posix compliant. Under LinuxThreads, a lock created by thread
30363 ** A cannot be modified or overridden by a different thread B.
30364 ** Only thread A can modify the lock. Locking behavior is correct
30365 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
30366 ** on linux - with NPTL a lock created by thread A can override locks
30367 ** in thread B. But there is no way to know at compile-time which
30368 ** threading library is being used. So there is no way to know at
30369 ** compile-time whether or not thread A can override locks on thread B.
30370 ** One has to do a run-time check to discover the behavior of the
30371 ** current process.
30372 **
30373 ** SQLite used to support LinuxThreads. But support for LinuxThreads
30374 ** was dropped beginning with version 3.7.0. SQLite will still work with
30375 ** LinuxThreads provided that (1) there is no more than one connection
30376 ** per database file in the same process and (2) database connections
30377 ** do not move across threads.
30378 */
30379 
30380 /*
30381 ** An instance of the following structure serves as the key used
30382 ** to locate a particular unixInodeInfo object.
30383 */
30384 struct unixFileId {
30385  dev_t dev; /* Device number */
30386 #if OS_VXWORKS
30387  struct vxworksFileId *pId; /* Unique file ID for vxworks. */
30388 #else
30389  ino_t ino; /* Inode number */
30390 #endif
30391 };
30392 
30393 /*
30394 ** An instance of the following structure is allocated for each open
30395 ** inode. Or, on LinuxThreads, there is one of these structures for
30396 ** each inode opened by each thread.
30397 **
30398 ** A single inode can have multiple file descriptors, so each unixFile
30399 ** structure contains a pointer to an instance of this object and this
30400 ** object keeps a count of the number of unixFile pointing to it.
30401 */
30402 struct unixInodeInfo {
30403  struct unixFileId fileId; /* The lookup key */
30404  int nShared; /* Number of SHARED locks held */
30405  unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
30406  unsigned char bProcessLock; /* An exclusive process lock is held */
30407  int nRef; /* Number of pointers to this structure */
30408  unixShmNode *pShmNode; /* Shared memory associated with this inode */
30409  int nLock; /* Number of outstanding file locks */
30410  UnixUnusedFd *pUnused; /* Unused file descriptors to close */
30411  unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
30412  unixInodeInfo *pPrev; /* .... doubly linked */
30413 #if SQLITE_ENABLE_LOCKING_STYLE
30414  unsigned long long sharedByte; /* for AFP simulated shared lock */
30415 #endif
30416 #if OS_VXWORKS
30417  sem_t *pSem; /* Named POSIX semaphore */
30418  char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
30419 #endif
30420 };
30421 
30422 /*
30423 ** A lists of all unixInodeInfo objects.
30424 */
30425 static unixInodeInfo *inodeList = 0;
30426 
30427 /*
30428 **
30429 ** This function - unixLogErrorAtLine(), is only ever called via the macro
30430 ** unixLogError().
30431 **
30432 ** It is invoked after an error occurs in an OS function and errno has been
30433 ** set. It logs a message using sqlite3_log() containing the current value of
30434 ** errno and, if possible, the human-readable equivalent from strerror() or
30435 ** strerror_r().
30436 **
30437 ** The first argument passed to the macro should be the error code that
30438 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
30439 ** The two subsequent arguments should be the name of the OS function that
30440 ** failed (e.g. "unlink", "open") and the associated file-system path,
30441 ** if any.
30442 */
30443 #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
30444 static int unixLogErrorAtLine(
30445  int errcode, /* SQLite error code */
30446  const char *zFunc, /* Name of OS function that failed */
30447  const char *zPath, /* File path associated with error */
30448  int iLine /* Source line number where error occurred */
30449 ){
30450  char *zErr; /* Message from strerror() or equivalent */
30451  int iErrno = errno; /* Saved syscall error number */
30452 
30453  /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
30454  ** the strerror() function to obtain the human-readable error message
30455  ** equivalent to errno. Otherwise, use strerror_r().
30456  */
30457 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
30458  char aErr[80];
30459  memset(aErr, 0, sizeof(aErr));
30460  zErr = aErr;
30461 
30462  /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
30463  ** assume that the system provides the GNU version of strerror_r() that
30464  ** returns a pointer to a buffer containing the error message. That pointer
30465  ** may point to aErr[], or it may point to some static storage somewhere.
30466  ** Otherwise, assume that the system provides the POSIX version of
30467  ** strerror_r(), which always writes an error message into aErr[].
30468  **
30469  ** If the code incorrectly assumes that it is the POSIX version that is
30470  ** available, the error message will often be an empty string. Not a
30471  ** huge problem. Incorrectly concluding that the GNU version is available
30472  ** could lead to a segfault though.
30473  */
30474 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
30475  zErr =
30476 # endif
30477  strerror_r(iErrno, aErr, sizeof(aErr)-1);
30478 
30479 #elif SQLITE_THREADSAFE
30480  /* This is a threadsafe build, but strerror_r() is not available. */
30481  zErr = "";
30482 #else
30483  /* Non-threadsafe build, use strerror(). */
30484  zErr = strerror(iErrno);
30485 #endif
30486 
30487  if( zPath==0 ) zPath = "";
30488  sqlite3_log(errcode,
30489  "os_unix.c:%d: (%d) %s(%s) - %s",
30490  iLine, iErrno, zFunc, zPath, zErr
30491  );
30492 
30493  return errcode;
30494 }
30495 
30496 /*
30497 ** Close a file descriptor.
30498 **
30499 ** We assume that close() almost always works, since it is only in a
30500 ** very sick application or on a very sick platform that it might fail.
30501 ** If it does fail, simply leak the file descriptor, but do log the
30502 ** error.
30503 **
30504 ** Note that it is not safe to retry close() after EINTR since the
30505 ** file descriptor might have already been reused by another thread.
30506 ** So we don't even try to recover from an EINTR. Just log the error
30507 ** and move on.
30508 */
30509 static void robust_close(unixFile *pFile, int h, int lineno){
30510  if( osClose(h) ){
30511  unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
30512  pFile ? pFile->zPath : 0, lineno);
30513  }
30514 }
30515 
30516 /*
30517 ** Set the pFile->lastErrno. Do this in a subroutine as that provides
30518 ** a convenient place to set a breakpoint.
30519 */
30520 static void storeLastErrno(unixFile *pFile, int error){
30521  pFile->lastErrno = error;
30522 }
30523 
30524 /*
30525 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
30526 */
30527 static void closePendingFds(unixFile *pFile){
30528  unixInodeInfo *pInode = pFile->pInode;
30529  UnixUnusedFd *p;
30530  UnixUnusedFd *pNext;
30531  for(p=pInode->pUnused; p; p=pNext){
30532  pNext = p->pNext;
30533  robust_close(pFile, p->fd, __LINE__);
30534  sqlite3_free(p);
30535  }
30536  pInode->pUnused = 0;
30537 }
30538 
30539 /*
30540 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
30541 **
30542 ** The mutex entered using the unixEnterMutex() function must be held
30543 ** when this function is called.
30544 */
30545 static void releaseInodeInfo(unixFile *pFile){
30546  unixInodeInfo *pInode = pFile->pInode;
30547  assert( unixMutexHeld() );
30548  if( ALWAYS(pInode) ){
30549  pInode->nRef--;
30550  if( pInode->nRef==0 ){
30551  assert( pInode->pShmNode==0 );
30552  closePendingFds(pFile);
30553  if( pInode->pPrev ){
30554  assert( pInode->pPrev->pNext==pInode );
30555  pInode->pPrev->pNext = pInode->pNext;
30556  }else{
30557  assert( inodeList==pInode );
30558  inodeList = pInode->pNext;
30559  }
30560  if( pInode->pNext ){
30561  assert( pInode->pNext->pPrev==pInode );
30562  pInode->pNext->pPrev = pInode->pPrev;
30563  }
30564  sqlite3_free(pInode);
30565  }
30566  }
30567 }
30568 
30569 /*
30570 ** Given a file descriptor, locate the unixInodeInfo object that
30571 ** describes that file descriptor. Create a new one if necessary. The
30572 ** return value might be uninitialized if an error occurs.
30573 **
30574 ** The mutex entered using the unixEnterMutex() function must be held
30575 ** when this function is called.
30576 **
30577 ** Return an appropriate error code.
30578 */
30579 static int findInodeInfo(
30580  unixFile *pFile, /* Unix file with file desc used in the key */
30581  unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
30582 ){
30583  int rc; /* System call return code */
30584  int fd; /* The file descriptor for pFile */
30585  struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
30586  struct stat statbuf; /* Low-level file information */
30587  unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
30588 
30589  assert( unixMutexHeld() );
30590 
30591  /* Get low-level information about the file that we can used to
30592  ** create a unique name for the file.
30593  */
30594  fd = pFile->h;
30595  rc = osFstat(fd, &statbuf);
30596  if( rc!=0 ){
30597  storeLastErrno(pFile, errno);
30598 #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
30599  if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
30600 #endif
30601  return SQLITE_IOERR;
30602  }
30603 
30604 #ifdef __APPLE__
30605  /* On OS X on an msdos filesystem, the inode number is reported
30606  ** incorrectly for zero-size files. See ticket #3260. To work
30607  ** around this problem (we consider it a bug in OS X, not SQLite)
30608  ** we always increase the file size to 1 by writing a single byte
30609  ** prior to accessing the inode number. The one byte written is
30610  ** an ASCII 'S' character which also happens to be the first byte
30611  ** in the header of every SQLite database. In this way, if there
30612  ** is a race condition such that another thread has already populated
30613  ** the first page of the database, no damage is done.
30614  */
30615  if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
30616  do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
30617  if( rc!=1 ){
30618  storeLastErrno(pFile, errno);
30619  return SQLITE_IOERR;
30620  }
30621  rc = osFstat(fd, &statbuf);
30622  if( rc!=0 ){
30623  storeLastErrno(pFile, errno);
30624  return SQLITE_IOERR;
30625  }
30626  }
30627 #endif
30628 
30629  memset(&fileId, 0, sizeof(fileId));
30630  fileId.dev = statbuf.st_dev;
30631 #if OS_VXWORKS
30632  fileId.pId = pFile->pId;
30633 #else
30634  fileId.ino = statbuf.st_ino;
30635 #endif
30636  pInode = inodeList;
30637  while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
30638  pInode = pInode->pNext;
30639  }
30640  if( pInode==0 ){
30641  pInode = sqlite3_malloc64( sizeof(*pInode) );
30642  if( pInode==0 ){
30643  return SQLITE_NOMEM_BKPT;
30644  }
30645  memset(pInode, 0, sizeof(*pInode));
30646  memcpy(&pInode->fileId, &fileId, sizeof(fileId));
30647  pInode->nRef = 1;
30648  pInode->pNext = inodeList;
30649  pInode->pPrev = 0;
30650  if( inodeList ) inodeList->pPrev = pInode;
30651  inodeList = pInode;
30652  }else{
30653  pInode->nRef++;
30654  }
30655  *ppInode = pInode;
30656  return SQLITE_OK;
30657 }
30658 
30659 /*
30660 ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
30661 */
30662 static int fileHasMoved(unixFile *pFile){
30663 #if OS_VXWORKS
30664  return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
30665 #else
30666  struct stat buf;
30667  return pFile->pInode!=0 &&
30668  (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
30669 #endif
30670 }
30671 
30672 
30673 /*
30674 ** Check a unixFile that is a database. Verify the following:
30675 **
30676 ** (1) There is exactly one hard link on the file
30677 ** (2) The file is not a symbolic link
30678 ** (3) The file has not been renamed or unlinked
30679 **
30680 ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
30681 */
30682 static void verifyDbFile(unixFile *pFile){
30683  struct stat buf;
30684  int rc;
30685 
30686  /* These verifications occurs for the main database only */
30687  if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
30688 
30689  rc = osFstat(pFile->h, &buf);
30690  if( rc!=0 ){
30691  sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
30692  return;
30693  }
30694  if( buf.st_nlink==0 ){
30695  sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
30696  return;
30697  }
30698  if( buf.st_nlink>1 ){
30699  sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
30700  return;
30701  }
30702  if( fileHasMoved(pFile) ){
30703  sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
30704  return;
30705  }
30706 }
30707 
30708 
30709 /*
30710 ** This routine checks if there is a RESERVED lock held on the specified
30711 ** file by this or any other process. If such a lock is held, set *pResOut
30712 ** to a non-zero value otherwise *pResOut is set to zero. The return value
30713 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
30714 */
30715 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
30716  int rc = SQLITE_OK;
30717  int reserved = 0;
30718  unixFile *pFile = (unixFile*)id;
30719 
30720  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
30721 
30722  assert( pFile );
30723  assert( pFile->eFileLock<=SHARED_LOCK );
30724  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
30725 
30726  /* Check if a thread in this process holds such a lock */
30727  if( pFile->pInode->eFileLock>SHARED_LOCK ){
30728  reserved = 1;
30729  }
30730 
30731  /* Otherwise see if some other process holds it.
30732  */
30733 #ifndef __DJGPP__
30734  if( !reserved && !pFile->pInode->bProcessLock ){
30735  struct flock lock;
30736  lock.l_whence = SEEK_SET;
30737  lock.l_start = RESERVED_BYTE;
30738  lock.l_len = 1;
30739  lock.l_type = F_WRLCK;
30740  if( osFcntl(pFile->h, F_GETLK, &lock) ){
30741  rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
30742  storeLastErrno(pFile, errno);
30743  } else if( lock.l_type!=F_UNLCK ){
30744  reserved = 1;
30745  }
30746  }
30747 #endif
30748 
30749  unixLeaveMutex();
30750  OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
30751 
30752  *pResOut = reserved;
30753  return rc;
30754 }
30755 
30756 /*
30757 ** Attempt to set a system-lock on the file pFile. The lock is
30758 ** described by pLock.
30759 **
30760 ** If the pFile was opened read/write from unix-excl, then the only lock
30761 ** ever obtained is an exclusive lock, and it is obtained exactly once
30762 ** the first time any lock is attempted. All subsequent system locking
30763 ** operations become no-ops. Locking operations still happen internally,
30764 ** in order to coordinate access between separate database connections
30765 ** within this process, but all of that is handled in memory and the
30766 ** operating system does not participate.
30767 **
30768 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
30769 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
30770 ** and is read-only.
30771 **
30772 ** Zero is returned if the call completes successfully, or -1 if a call
30773 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
30774 */
30775 static int unixFileLock(unixFile *pFile, struct flock *pLock){
30776  int rc;
30777  unixInodeInfo *pInode = pFile->pInode;
30778  assert( unixMutexHeld() );
30779  assert( pInode!=0 );
30780  if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
30781  if( pInode->bProcessLock==0 ){
30782  struct flock lock;
30783  assert( pInode->nLock==0 );
30784  lock.l_whence = SEEK_SET;
30785  lock.l_start = SHARED_FIRST;
30786  lock.l_len = SHARED_SIZE;
30787  lock.l_type = F_WRLCK;
30788  rc = osFcntl(pFile->h, F_SETLK, &lock);
30789  if( rc<0 ) return rc;
30790  pInode->bProcessLock = 1;
30791  pInode->nLock++;
30792  }else{
30793  rc = 0;
30794  }
30795  }else{
30796  rc = osFcntl(pFile->h, F_SETLK, pLock);
30797  }
30798  return rc;
30799 }
30800 
30801 /*
30802 ** Lock the file with the lock specified by parameter eFileLock - one
30803 ** of the following:
30804 **
30805 ** (1) SHARED_LOCK
30806 ** (2) RESERVED_LOCK
30807 ** (3) PENDING_LOCK
30808 ** (4) EXCLUSIVE_LOCK
30809 **
30810 ** Sometimes when requesting one lock state, additional lock states
30811 ** are inserted in between. The locking might fail on one of the later
30812 ** transitions leaving the lock state different from what it started but
30813 ** still short of its goal. The following chart shows the allowed
30814 ** transitions and the inserted intermediate states:
30815 **
30816 ** UNLOCKED -> SHARED
30817 ** SHARED -> RESERVED
30818 ** SHARED -> (PENDING) -> EXCLUSIVE
30819 ** RESERVED -> (PENDING) -> EXCLUSIVE
30820 ** PENDING -> EXCLUSIVE
30821 **
30822 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
30823 ** routine to lower a locking level.
30824 */
30825 static int unixLock(sqlite3_file *id, int eFileLock){
30826  /* The following describes the implementation of the various locks and
30827  ** lock transitions in terms of the POSIX advisory shared and exclusive
30828  ** lock primitives (called read-locks and write-locks below, to avoid
30829  ** confusion with SQLite lock names). The algorithms are complicated
30830  ** slightly in order to be compatible with Windows95 systems simultaneously
30831  ** accessing the same database file, in case that is ever required.
30832  **
30833  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
30834  ** byte', each single bytes at well known offsets, and the 'shared byte
30835  ** range', a range of 510 bytes at a well known offset.
30836  **
30837  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
30838  ** byte'. If this is successful, 'shared byte range' is read-locked
30839  ** and the lock on the 'pending byte' released. (Legacy note: When
30840  ** SQLite was first developed, Windows95 systems were still very common,
30841  ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
30842  ** single randomly selected by from the 'shared byte range' is locked.
30843  ** Windows95 is now pretty much extinct, but this work-around for the
30844  ** lack of shared-locks on Windows95 lives on, for backwards
30845  ** compatibility.)
30846  **
30847  ** A process may only obtain a RESERVED lock after it has a SHARED lock.
30848  ** A RESERVED lock is implemented by grabbing a write-lock on the
30849  ** 'reserved byte'.
30850  **
30851  ** A process may only obtain a PENDING lock after it has obtained a
30852  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
30853  ** on the 'pending byte'. This ensures that no new SHARED locks can be
30854  ** obtained, but existing SHARED locks are allowed to persist. A process
30855  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
30856  ** This property is used by the algorithm for rolling back a journal file
30857  ** after a crash.
30858  **
30859  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
30860  ** implemented by obtaining a write-lock on the entire 'shared byte
30861  ** range'. Since all other locks require a read-lock on one of the bytes
30862  ** within this range, this ensures that no other locks are held on the
30863  ** database.
30864  */
30865  int rc = SQLITE_OK;
30866  unixFile *pFile = (unixFile*)id;
30867  unixInodeInfo *pInode;
30868  struct flock lock;
30869  int tErrno = 0;
30870 
30871  assert( pFile );
30872  OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
30873  azFileLock(eFileLock), azFileLock(pFile->eFileLock),
30874  azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
30875  osGetpid(0)));
30876 
30877  /* If there is already a lock of this type or more restrictive on the
30878  ** unixFile, do nothing. Don't use the end_lock: exit path, as
30879  ** unixEnterMutex() hasn't been called yet.
30880  */
30881  if( pFile->eFileLock>=eFileLock ){
30882  OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
30883  azFileLock(eFileLock)));
30884  return SQLITE_OK;
30885  }
30886 
30887  /* Make sure the locking sequence is correct.
30888  ** (1) We never move from unlocked to anything higher than shared lock.
30889  ** (2) SQLite never explicitly requests a pendig lock.
30890  ** (3) A shared lock is always held when a reserve lock is requested.
30891  */
30892  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
30893  assert( eFileLock!=PENDING_LOCK );
30894  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
30895 
30896  /* This mutex is needed because pFile->pInode is shared across threads
30897  */
30898  unixEnterMutex();
30899  pInode = pFile->pInode;
30900 
30901  /* If some thread using this PID has a lock via a different unixFile*
30902  ** handle that precludes the requested lock, return BUSY.
30903  */
30904  if( (pFile->eFileLock!=pInode->eFileLock &&
30905  (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
30906  ){
30907  rc = SQLITE_BUSY;
30908  goto end_lock;
30909  }
30910 
30911  /* If a SHARED lock is requested, and some thread using this PID already
30912  ** has a SHARED or RESERVED lock, then increment reference counts and
30913  ** return SQLITE_OK.
30914  */
30915  if( eFileLock==SHARED_LOCK &&
30916  (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
30917  assert( eFileLock==SHARED_LOCK );
30918  assert( pFile->eFileLock==0 );
30919  assert( pInode->nShared>0 );
30920  pFile->eFileLock = SHARED_LOCK;
30921  pInode->nShared++;
30922  pInode->nLock++;
30923  goto end_lock;
30924  }
30925 
30926 
30927  /* A PENDING lock is needed before acquiring a SHARED lock and before
30928  ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
30929  ** be released.
30930  */
30931  lock.l_len = 1L;
30932  lock.l_whence = SEEK_SET;
30933  if( eFileLock==SHARED_LOCK
30934  || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
30935  ){
30936  lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
30937  lock.l_start = PENDING_BYTE;
30938  if( unixFileLock(pFile, &lock) ){
30939  tErrno = errno;
30940  rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
30941  if( rc!=SQLITE_BUSY ){
30942  storeLastErrno(pFile, tErrno);
30943  }
30944  goto end_lock;
30945  }
30946  }
30947 
30948 
30949  /* If control gets to this point, then actually go ahead and make
30950  ** operating system calls for the specified lock.
30951  */
30952  if( eFileLock==SHARED_LOCK ){
30953  assert( pInode->nShared==0 );
30954  assert( pInode->eFileLock==0 );
30955  assert( rc==SQLITE_OK );
30956 
30957  /* Now get the read-lock */
30958  lock.l_start = SHARED_FIRST;
30959  lock.l_len = SHARED_SIZE;
30960  if( unixFileLock(pFile, &lock) ){
30961  tErrno = errno;
30962  rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
30963  }
30964 
30965  /* Drop the temporary PENDING lock */
30966  lock.l_start = PENDING_BYTE;
30967  lock.l_len = 1L;
30968  lock.l_type = F_UNLCK;
30969  if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
30970  /* This could happen with a network mount */
30971  tErrno = errno;
30972  rc = SQLITE_IOERR_UNLOCK;
30973  }
30974 
30975  if( rc ){
30976  if( rc!=SQLITE_BUSY ){
30977  storeLastErrno(pFile, tErrno);
30978  }
30979  goto end_lock;
30980  }else{
30981  pFile->eFileLock = SHARED_LOCK;
30982  pInode->nLock++;
30983  pInode->nShared = 1;
30984  }
30985  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
30986  /* We are trying for an exclusive lock but another thread in this
30987  ** same process is still holding a shared lock. */
30988  rc = SQLITE_BUSY;
30989  }else{
30990  /* The request was for a RESERVED or EXCLUSIVE lock. It is
30991  ** assumed that there is a SHARED or greater lock on the file
30992  ** already.
30993  */
30994  assert( 0!=pFile->eFileLock );
30995  lock.l_type = F_WRLCK;
30996 
30997  assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
30998  if( eFileLock==RESERVED_LOCK ){
30999  lock.l_start = RESERVED_BYTE;
31000  lock.l_len = 1L;
31001  }else{
31002  lock.l_start = SHARED_FIRST;
31003  lock.l_len = SHARED_SIZE;
31004  }
31005 
31006  if( unixFileLock(pFile, &lock) ){
31007  tErrno = errno;
31008  rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
31009  if( rc!=SQLITE_BUSY ){
31010  storeLastErrno(pFile, tErrno);
31011  }
31012  }
31013  }
31014 
31015 
31016 #ifdef SQLITE_DEBUG
31017  /* Set up the transaction-counter change checking flags when
31018  ** transitioning from a SHARED to a RESERVED lock. The change
31019  ** from SHARED to RESERVED marks the beginning of a normal
31020  ** write operation (not a hot journal rollback).
31021  */
31022  if( rc==SQLITE_OK
31023  && pFile->eFileLock<=SHARED_LOCK
31024  && eFileLock==RESERVED_LOCK
31025  ){
31026  pFile->transCntrChng = 0;
31027  pFile->dbUpdate = 0;
31028  pFile->inNormalWrite = 1;
31029  }
31030 #endif
31031 
31032 
31033  if( rc==SQLITE_OK ){
31034  pFile->eFileLock = eFileLock;
31035  pInode->eFileLock = eFileLock;
31036  }else if( eFileLock==EXCLUSIVE_LOCK ){
31037  pFile->eFileLock = PENDING_LOCK;
31038  pInode->eFileLock = PENDING_LOCK;
31039  }
31040 
31041 end_lock:
31042  unixLeaveMutex();
31043  OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
31044  rc==SQLITE_OK ? "ok" : "failed"));
31045  return rc;
31046 }
31047 
31048 /*
31049 ** Add the file descriptor used by file handle pFile to the corresponding
31050 ** pUnused list.
31051 */
31052 static void setPendingFd(unixFile *pFile){
31053  unixInodeInfo *pInode = pFile->pInode;
31054  UnixUnusedFd *p = pFile->pUnused;
31055  p->pNext = pInode->pUnused;
31056  pInode->pUnused = p;
31057  pFile->h = -1;
31058  pFile->pUnused = 0;
31059 }
31060 
31061 /*
31062 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
31063 ** must be either NO_LOCK or SHARED_LOCK.
31064 **
31065 ** If the locking level of the file descriptor is already at or below
31066 ** the requested locking level, this routine is a no-op.
31067 **
31068 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
31069 ** the byte range is divided into 2 parts and the first part is unlocked then
31070 ** set to a read lock, then the other part is simply unlocked. This works
31071 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
31072 ** remove the write lock on a region when a read lock is set.
31073 */
31074 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
31075  unixFile *pFile = (unixFile*)id;
31076  unixInodeInfo *pInode;
31077  struct flock lock;
31078  int rc = SQLITE_OK;
31079 
31080  assert( pFile );
31081  OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
31082  pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
31083  osGetpid(0)));
31084 
31085  assert( eFileLock<=SHARED_LOCK );
31086  if( pFile->eFileLock<=eFileLock ){
31087  return SQLITE_OK;
31088  }
31089  unixEnterMutex();
31090  pInode = pFile->pInode;
31091  assert( pInode->nShared!=0 );
31092  if( pFile->eFileLock>SHARED_LOCK ){
31093  assert( pInode->eFileLock==pFile->eFileLock );
31094 
31095 #ifdef SQLITE_DEBUG
31096  /* When reducing a lock such that other processes can start
31097  ** reading the database file again, make sure that the
31098  ** transaction counter was updated if any part of the database
31099  ** file changed. If the transaction counter is not updated,
31100  ** other connections to the same file might not realize that
31101  ** the file has changed and hence might not know to flush their
31102  ** cache. The use of a stale cache can lead to database corruption.
31103  */
31104  pFile->inNormalWrite = 0;
31105 #endif
31106 
31107  /* downgrading to a shared lock on NFS involves clearing the write lock
31108  ** before establishing the readlock - to avoid a race condition we downgrade
31109  ** the lock in 2 blocks, so that part of the range will be covered by a
31110  ** write lock until the rest is covered by a read lock:
31111  ** 1: [WWWWW]
31112  ** 2: [....W]
31113  ** 3: [RRRRW]
31114  ** 4: [RRRR.]
31115  */
31116  if( eFileLock==SHARED_LOCK ){
31117 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
31118  (void)handleNFSUnlock;
31119  assert( handleNFSUnlock==0 );
31120 #endif
31121 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31122  if( handleNFSUnlock ){
31123  int tErrno; /* Error code from system call errors */
31124  off_t divSize = SHARED_SIZE - 1;
31125 
31126  lock.l_type = F_UNLCK;
31127  lock.l_whence = SEEK_SET;
31128  lock.l_start = SHARED_FIRST;
31129  lock.l_len = divSize;
31130  if( unixFileLock(pFile, &lock)==(-1) ){
31131  tErrno = errno;
31132  rc = SQLITE_IOERR_UNLOCK;
31133  storeLastErrno(pFile, tErrno);
31134  goto end_unlock;
31135  }
31136  lock.l_type = F_RDLCK;
31137  lock.l_whence = SEEK_SET;
31138  lock.l_start = SHARED_FIRST;
31139  lock.l_len = divSize;
31140  if( unixFileLock(pFile, &lock)==(-1) ){
31141  tErrno = errno;
31142  rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
31143  if( IS_LOCK_ERROR(rc) ){
31144  storeLastErrno(pFile, tErrno);
31145  }
31146  goto end_unlock;
31147  }
31148  lock.l_type = F_UNLCK;
31149  lock.l_whence = SEEK_SET;
31150  lock.l_start = SHARED_FIRST+divSize;
31151  lock.l_len = SHARED_SIZE-divSize;
31152  if( unixFileLock(pFile, &lock)==(-1) ){
31153  tErrno = errno;
31154  rc = SQLITE_IOERR_UNLOCK;
31155  storeLastErrno(pFile, tErrno);
31156  goto end_unlock;
31157  }
31158  }else
31159 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
31160  {
31161  lock.l_type = F_RDLCK;
31162  lock.l_whence = SEEK_SET;
31163  lock.l_start = SHARED_FIRST;
31164  lock.l_len = SHARED_SIZE;
31165  if( unixFileLock(pFile, &lock) ){
31166  /* In theory, the call to unixFileLock() cannot fail because another
31167  ** process is holding an incompatible lock. If it does, this
31168  ** indicates that the other process is not following the locking
31169  ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
31170  ** SQLITE_BUSY would confuse the upper layer (in practice it causes
31171  ** an assert to fail). */
31172  rc = SQLITE_IOERR_RDLOCK;
31173  storeLastErrno(pFile, errno);
31174  goto end_unlock;
31175  }
31176  }
31177  }
31178  lock.l_type = F_UNLCK;
31179  lock.l_whence = SEEK_SET;
31180  lock.l_start = PENDING_BYTE;
31181  lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
31182  if( unixFileLock(pFile, &lock)==0 ){
31183  pInode->eFileLock = SHARED_LOCK;
31184  }else{
31185  rc = SQLITE_IOERR_UNLOCK;
31186  storeLastErrno(pFile, errno);
31187  goto end_unlock;
31188  }
31189  }
31190  if( eFileLock==NO_LOCK ){
31191  /* Decrement the shared lock counter. Release the lock using an
31192  ** OS call only when all threads in this same process have released
31193  ** the lock.
31194  */
31195  pInode->nShared--;
31196  if( pInode->nShared==0 ){
31197  lock.l_type = F_UNLCK;
31198  lock.l_whence = SEEK_SET;
31199  lock.l_start = lock.l_len = 0L;
31200  if( unixFileLock(pFile, &lock)==0 ){
31201  pInode->eFileLock = NO_LOCK;
31202  }else{
31203  rc = SQLITE_IOERR_UNLOCK;
31204  storeLastErrno(pFile, errno);
31205  pInode->eFileLock = NO_LOCK;
31206  pFile->eFileLock = NO_LOCK;
31207  }
31208  }
31209 
31210  /* Decrement the count of locks against this same file. When the
31211  ** count reaches zero, close any other file descriptors whose close
31212  ** was deferred because of outstanding locks.
31213  */
31214  pInode->nLock--;
31215  assert( pInode->nLock>=0 );
31216  if( pInode->nLock==0 ){
31217  closePendingFds(pFile);
31218  }
31219  }
31220 
31221 end_unlock:
31222  unixLeaveMutex();
31223  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
31224  return rc;
31225 }
31226 
31227 /*
31228 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
31229 ** must be either NO_LOCK or SHARED_LOCK.
31230 **
31231 ** If the locking level of the file descriptor is already at or below
31232 ** the requested locking level, this routine is a no-op.
31233 */
31234 static int unixUnlock(sqlite3_file *id, int eFileLock){
31235 #if SQLITE_MAX_MMAP_SIZE>0
31236  assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
31237 #endif
31238  return posixUnlock(id, eFileLock, 0);
31239 }
31240 
31241 #if SQLITE_MAX_MMAP_SIZE>0
31242 static int unixMapfile(unixFile *pFd, i64 nByte);
31243 static void unixUnmapfile(unixFile *pFd);
31244 #endif
31245 
31246 /*
31247 ** This function performs the parts of the "close file" operation
31248 ** common to all locking schemes. It closes the directory and file
31249 ** handles, if they are valid, and sets all fields of the unixFile
31250 ** structure to 0.
31251 **
31252 ** It is *not* necessary to hold the mutex when this routine is called,
31253 ** even on VxWorks. A mutex will be acquired on VxWorks by the
31254 ** vxworksReleaseFileId() routine.
31255 */
31256 static int closeUnixFile(sqlite3_file *id){
31257  unixFile *pFile = (unixFile*)id;
31258 #if SQLITE_MAX_MMAP_SIZE>0
31259  unixUnmapfile(pFile);
31260 #endif
31261  if( pFile->h>=0 ){
31262  robust_close(pFile, pFile->h, __LINE__);
31263  pFile->h = -1;
31264  }
31265 #if OS_VXWORKS
31266  if( pFile->pId ){
31267  if( pFile->ctrlFlags & UNIXFILE_DELETE ){
31268  osUnlink(pFile->pId->zCanonicalName);
31269  }
31270  vxworksReleaseFileId(pFile->pId);
31271  pFile->pId = 0;
31272  }
31273 #endif
31274 #ifdef SQLITE_UNLINK_AFTER_CLOSE
31275  if( pFile->ctrlFlags & UNIXFILE_DELETE ){
31276  osUnlink(pFile->zPath);
31277  sqlite3_free(*(char**)&pFile->zPath);
31278  pFile->zPath = 0;
31279  }
31280 #endif
31281  OSTRACE(("CLOSE %-3d\n", pFile->h));
31282  OpenCounter(-1);
31283  sqlite3_free(pFile->pUnused);
31284  memset(pFile, 0, sizeof(unixFile));
31285  return SQLITE_OK;
31286 }
31287 
31288 /*
31289 ** Close a file.
31290 */
31291 static int unixClose(sqlite3_file *id){
31292  int rc = SQLITE_OK;
31293  unixFile *pFile = (unixFile *)id;
31294  verifyDbFile(pFile);
31295  unixUnlock(id, NO_LOCK);
31296  unixEnterMutex();
31297 
31298  /* unixFile.pInode is always valid here. Otherwise, a different close
31299  ** routine (e.g. nolockClose()) would be called instead.
31300  */
31301  assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
31302  if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
31303  /* If there are outstanding locks, do not actually close the file just
31304  ** yet because that would clear those locks. Instead, add the file
31305  ** descriptor to pInode->pUnused list. It will be automatically closed
31306  ** when the last lock is cleared.
31307  */
31308  setPendingFd(pFile);
31309  }
31310  releaseInodeInfo(pFile);
31311  rc = closeUnixFile(id);
31312  unixLeaveMutex();
31313  return rc;
31314 }
31315 
31316 /************** End of the posix advisory lock implementation *****************
31317 ******************************************************************************/
31318 
31319 /******************************************************************************
31320 ****************************** No-op Locking **********************************
31321 **
31322 ** Of the various locking implementations available, this is by far the
31323 ** simplest: locking is ignored. No attempt is made to lock the database
31324 ** file for reading or writing.
31325 **
31326 ** This locking mode is appropriate for use on read-only databases
31327 ** (ex: databases that are burned into CD-ROM, for example.) It can
31328 ** also be used if the application employs some external mechanism to
31329 ** prevent simultaneous access of the same database by two or more
31330 ** database connections. But there is a serious risk of database
31331 ** corruption if this locking mode is used in situations where multiple
31332 ** database connections are accessing the same database file at the same
31333 ** time and one or more of those connections are writing.
31334 */
31335 
31336 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
31337  UNUSED_PARAMETER(NotUsed);
31338  *pResOut = 0;
31339  return SQLITE_OK;
31340 }
31341 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
31342  UNUSED_PARAMETER2(NotUsed, NotUsed2);
31343  return SQLITE_OK;
31344 }
31345 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
31346  UNUSED_PARAMETER2(NotUsed, NotUsed2);
31347  return SQLITE_OK;
31348 }
31349 
31350 /*
31351 ** Close the file.
31352 */
31353 static int nolockClose(sqlite3_file *id) {
31354  return closeUnixFile(id);
31355 }
31356 
31357 /******************* End of the no-op lock implementation *********************
31358 ******************************************************************************/
31359 
31360 /******************************************************************************
31361 ************************* Begin dot-file Locking ******************************
31362 **
31363 ** The dotfile locking implementation uses the existence of separate lock
31364 ** files (really a directory) to control access to the database. This works
31365 ** on just about every filesystem imaginable. But there are serious downsides:
31366 **
31367 ** (1) There is zero concurrency. A single reader blocks all other
31368 ** connections from reading or writing the database.
31369 **
31370 ** (2) An application crash or power loss can leave stale lock files
31371 ** sitting around that need to be cleared manually.
31372 **
31373 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
31374 ** other locking strategy is available.
31375 **
31376 ** Dotfile locking works by creating a subdirectory in the same directory as
31377 ** the database and with the same name but with a ".lock" extension added.
31378 ** The existence of a lock directory implies an EXCLUSIVE lock. All other
31379 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
31380 */
31381 
31382 /*
31383 ** The file suffix added to the data base filename in order to create the
31384 ** lock directory.
31385 */
31386 #define DOTLOCK_SUFFIX ".lock"
31387 
31388 /*
31389 ** This routine checks if there is a RESERVED lock held on the specified
31390 ** file by this or any other process. If such a lock is held, set *pResOut
31391 ** to a non-zero value otherwise *pResOut is set to zero. The return value
31392 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31393 **
31394 ** In dotfile locking, either a lock exists or it does not. So in this
31395 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
31396 ** is held on the file and false if the file is unlocked.
31397 */
31398 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
31399  int rc = SQLITE_OK;
31400  int reserved = 0;
31401  unixFile *pFile = (unixFile*)id;
31402 
31403  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
31404 
31405  assert( pFile );
31406  reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
31407  OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
31408  *pResOut = reserved;
31409  return rc;
31410 }
31411 
31412 /*
31413 ** Lock the file with the lock specified by parameter eFileLock - one
31414 ** of the following:
31415 **
31416 ** (1) SHARED_LOCK
31417 ** (2) RESERVED_LOCK
31418 ** (3) PENDING_LOCK
31419 ** (4) EXCLUSIVE_LOCK
31420 **
31421 ** Sometimes when requesting one lock state, additional lock states
31422 ** are inserted in between. The locking might fail on one of the later
31423 ** transitions leaving the lock state different from what it started but
31424 ** still short of its goal. The following chart shows the allowed
31425 ** transitions and the inserted intermediate states:
31426 **
31427 ** UNLOCKED -> SHARED
31428 ** SHARED -> RESERVED
31429 ** SHARED -> (PENDING) -> EXCLUSIVE
31430 ** RESERVED -> (PENDING) -> EXCLUSIVE
31431 ** PENDING -> EXCLUSIVE
31432 **
31433 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
31434 ** routine to lower a locking level.
31435 **
31436 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
31437 ** But we track the other locking levels internally.
31438 */
31439 static int dotlockLock(sqlite3_file *id, int eFileLock) {
31440  unixFile *pFile = (unixFile*)id;
31441  char *zLockFile = (char *)pFile->lockingContext;
31442  int rc = SQLITE_OK;
31443 
31444 
31445  /* If we have any lock, then the lock file already exists. All we have
31446  ** to do is adjust our internal record of the lock level.
31447  */
31448  if( pFile->eFileLock > NO_LOCK ){
31449  pFile->eFileLock = eFileLock;
31450  /* Always update the timestamp on the old file */
31451 #ifdef HAVE_UTIME
31452  utime(zLockFile, NULL);
31453 #else
31454  utimes(zLockFile, NULL);
31455 #endif
31456  return SQLITE_OK;
31457  }
31458 
31459  /* grab an exclusive lock */
31460  rc = osMkdir(zLockFile, 0777);
31461  if( rc<0 ){
31462  /* failed to open/create the lock directory */
31463  int tErrno = errno;
31464  if( EEXIST == tErrno ){
31465  rc = SQLITE_BUSY;
31466  } else {
31467  rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
31468  if( rc!=SQLITE_BUSY ){
31469  storeLastErrno(pFile, tErrno);
31470  }
31471  }
31472  return rc;
31473  }
31474 
31475  /* got it, set the type and return ok */
31476  pFile->eFileLock = eFileLock;
31477  return rc;
31478 }
31479 
31480 /*
31481 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
31482 ** must be either NO_LOCK or SHARED_LOCK.
31483 **
31484 ** If the locking level of the file descriptor is already at or below
31485 ** the requested locking level, this routine is a no-op.
31486 **
31487 ** When the locking level reaches NO_LOCK, delete the lock file.
31488 */
31489 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
31490  unixFile *pFile = (unixFile*)id;
31491  char *zLockFile = (char *)pFile->lockingContext;
31492  int rc;
31493 
31494  assert( pFile );
31495  OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
31496  pFile->eFileLock, osGetpid(0)));
31497  assert( eFileLock<=SHARED_LOCK );
31498 
31499  /* no-op if possible */
31500  if( pFile->eFileLock==eFileLock ){
31501  return SQLITE_OK;
31502  }
31503 
31504  /* To downgrade to shared, simply update our internal notion of the
31505  ** lock state. No need to mess with the file on disk.
31506  */
31507  if( eFileLock==SHARED_LOCK ){
31508  pFile->eFileLock = SHARED_LOCK;
31509  return SQLITE_OK;
31510  }
31511 
31512  /* To fully unlock the database, delete the lock file */
31513  assert( eFileLock==NO_LOCK );
31514  rc = osRmdir(zLockFile);
31515  if( rc<0 ){
31516  int tErrno = errno;
31517  if( tErrno==ENOENT ){
31518  rc = SQLITE_OK;
31519  }else{
31520  rc = SQLITE_IOERR_UNLOCK;
31521  storeLastErrno(pFile, tErrno);
31522  }
31523  return rc;
31524  }
31525  pFile->eFileLock = NO_LOCK;
31526  return SQLITE_OK;
31527 }
31528 
31529 /*
31530 ** Close a file. Make sure the lock has been released before closing.
31531 */
31532 static int dotlockClose(sqlite3_file *id) {
31533  unixFile *pFile = (unixFile*)id;
31534  assert( id!=0 );
31535  dotlockUnlock(id, NO_LOCK);
31536  sqlite3_free(pFile->lockingContext);
31537  return closeUnixFile(id);
31538 }
31539 /****************** End of the dot-file lock implementation *******************
31540 ******************************************************************************/
31541 
31542 /******************************************************************************
31543 ************************** Begin flock Locking ********************************
31544 **
31545 ** Use the flock() system call to do file locking.
31546 **
31547 ** flock() locking is like dot-file locking in that the various
31548 ** fine-grain locking levels supported by SQLite are collapsed into
31549 ** a single exclusive lock. In other words, SHARED, RESERVED, and
31550 ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
31551 ** still works when you do this, but concurrency is reduced since
31552 ** only a single process can be reading the database at a time.
31553 **
31554 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
31555 */
31556 #if SQLITE_ENABLE_LOCKING_STYLE
31557 
31558 /*
31559 ** Retry flock() calls that fail with EINTR
31560 */
31561 #ifdef EINTR
31562 static int robust_flock(int fd, int op){
31563  int rc;
31564  do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
31565  return rc;
31566 }
31567 #else
31568 # define robust_flock(a,b) flock(a,b)
31569 #endif
31570 
31571 
31572 /*
31573 ** This routine checks if there is a RESERVED lock held on the specified
31574 ** file by this or any other process. If such a lock is held, set *pResOut
31575 ** to a non-zero value otherwise *pResOut is set to zero. The return value
31576 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31577 */
31578 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
31579  int rc = SQLITE_OK;
31580  int reserved = 0;
31581  unixFile *pFile = (unixFile*)id;
31582 
31583  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
31584 
31585  assert( pFile );
31586 
31587  /* Check if a thread in this process holds such a lock */
31588  if( pFile->eFileLock>SHARED_LOCK ){
31589  reserved = 1;
31590  }
31591 
31592  /* Otherwise see if some other process holds it. */
31593  if( !reserved ){
31594  /* attempt to get the lock */
31595  int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
31596  if( !lrc ){
31597  /* got the lock, unlock it */
31598  lrc = robust_flock(pFile->h, LOCK_UN);
31599  if ( lrc ) {
31600  int tErrno = errno;
31601  /* unlock failed with an error */
31602  lrc = SQLITE_IOERR_UNLOCK;
31603  storeLastErrno(pFile, tErrno);
31604  rc = lrc;
31605  }
31606  } else {
31607  int tErrno = errno;
31608  reserved = 1;
31609  /* someone else might have it reserved */
31610  lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
31611  if( IS_LOCK_ERROR(lrc) ){
31612  storeLastErrno(pFile, tErrno);
31613  rc = lrc;
31614  }
31615  }
31616  }
31617  OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
31618 
31619 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
31620  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
31621  rc = SQLITE_OK;
31622  reserved=1;
31623  }
31624 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
31625  *pResOut = reserved;
31626  return rc;
31627 }
31628 
31629 /*
31630 ** Lock the file with the lock specified by parameter eFileLock - one
31631 ** of the following:
31632 **
31633 ** (1) SHARED_LOCK
31634 ** (2) RESERVED_LOCK
31635 ** (3) PENDING_LOCK
31636 ** (4) EXCLUSIVE_LOCK
31637 **
31638 ** Sometimes when requesting one lock state, additional lock states
31639 ** are inserted in between. The locking might fail on one of the later
31640 ** transitions leaving the lock state different from what it started but
31641 ** still short of its goal. The following chart shows the allowed
31642 ** transitions and the inserted intermediate states:
31643 **
31644 ** UNLOCKED -> SHARED
31645 ** SHARED -> RESERVED
31646 ** SHARED -> (PENDING) -> EXCLUSIVE
31647 ** RESERVED -> (PENDING) -> EXCLUSIVE
31648 ** PENDING -> EXCLUSIVE
31649 **
31650 ** flock() only really support EXCLUSIVE locks. We track intermediate
31651 ** lock states in the sqlite3_file structure, but all locks SHARED or
31652 ** above are really EXCLUSIVE locks and exclude all other processes from
31653 ** access the file.
31654 **
31655 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
31656 ** routine to lower a locking level.
31657 */
31658 static int flockLock(sqlite3_file *id, int eFileLock) {
31659  int rc = SQLITE_OK;
31660  unixFile *pFile = (unixFile*)id;
31661 
31662  assert( pFile );
31663 
31664  /* if we already have a lock, it is exclusive.
31665  ** Just adjust level and punt on outta here. */
31666  if (pFile->eFileLock > NO_LOCK) {
31667  pFile->eFileLock = eFileLock;
31668  return SQLITE_OK;
31669  }
31670 
31671  /* grab an exclusive lock */
31672 
31673  if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
31674  int tErrno = errno;
31675  /* didn't get, must be busy */
31676  rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
31677  if( IS_LOCK_ERROR(rc) ){
31678  storeLastErrno(pFile, tErrno);
31679  }
31680  } else {
31681  /* got it, set the type and return ok */
31682  pFile->eFileLock = eFileLock;
31683  }
31684  OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
31685  rc==SQLITE_OK ? "ok" : "failed"));
31686 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
31687  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
31688  rc = SQLITE_BUSY;
31689  }
31690 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
31691  return rc;
31692 }
31693 
31694 
31695 /*
31696 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
31697 ** must be either NO_LOCK or SHARED_LOCK.
31698 **
31699 ** If the locking level of the file descriptor is already at or below
31700 ** the requested locking level, this routine is a no-op.
31701 */
31702 static int flockUnlock(sqlite3_file *id, int eFileLock) {
31703  unixFile *pFile = (unixFile*)id;
31704 
31705  assert( pFile );
31706  OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
31707  pFile->eFileLock, osGetpid(0)));
31708  assert( eFileLock<=SHARED_LOCK );
31709 
31710  /* no-op if possible */
31711  if( pFile->eFileLock==eFileLock ){
31712  return SQLITE_OK;
31713  }
31714 
31715  /* shared can just be set because we always have an exclusive */
31716  if (eFileLock==SHARED_LOCK) {
31717  pFile->eFileLock = eFileLock;
31718  return SQLITE_OK;
31719  }
31720 
31721  /* no, really, unlock. */
31722  if( robust_flock(pFile->h, LOCK_UN) ){
31723 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
31724  return SQLITE_OK;
31725 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
31726  return SQLITE_IOERR_UNLOCK;
31727  }else{
31728  pFile->eFileLock = NO_LOCK;
31729  return SQLITE_OK;
31730  }
31731 }
31732 
31733 /*
31734 ** Close a file.
31735 */
31736 static int flockClose(sqlite3_file *id) {
31737  assert( id!=0 );
31738  flockUnlock(id, NO_LOCK);
31739  return closeUnixFile(id);
31740 }
31741 
31742 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
31743 
31744 /******************* End of the flock lock implementation *********************
31745 ******************************************************************************/
31746 
31747 /******************************************************************************
31748 ************************ Begin Named Semaphore Locking ************************
31749 **
31750 ** Named semaphore locking is only supported on VxWorks.
31751 **
31752 ** Semaphore locking is like dot-lock and flock in that it really only
31753 ** supports EXCLUSIVE locking. Only a single process can read or write
31754 ** the database file at a time. This reduces potential concurrency, but
31755 ** makes the lock implementation much easier.
31756 */
31757 #if OS_VXWORKS
31758 
31759 /*
31760 ** This routine checks if there is a RESERVED lock held on the specified
31761 ** file by this or any other process. If such a lock is held, set *pResOut
31762 ** to a non-zero value otherwise *pResOut is set to zero. The return value
31763 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31764 */
31765 static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
31766  int rc = SQLITE_OK;
31767  int reserved = 0;
31768  unixFile *pFile = (unixFile*)id;
31769 
31770  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
31771 
31772  assert( pFile );
31773 
31774  /* Check if a thread in this process holds such a lock */
31775  if( pFile->eFileLock>SHARED_LOCK ){
31776  reserved = 1;
31777  }
31778 
31779  /* Otherwise see if some other process holds it. */
31780  if( !reserved ){
31781  sem_t *pSem = pFile->pInode->pSem;
31782 
31783  if( sem_trywait(pSem)==-1 ){
31784  int tErrno = errno;
31785  if( EAGAIN != tErrno ){
31786  rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
31787  storeLastErrno(pFile, tErrno);
31788  } else {
31789  /* someone else has the lock when we are in NO_LOCK */
31790  reserved = (pFile->eFileLock < SHARED_LOCK);
31791  }
31792  }else{
31793  /* we could have it if we want it */
31794  sem_post(pSem);
31795  }
31796  }
31797  OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
31798 
31799  *pResOut = reserved;
31800  return rc;
31801 }
31802 
31803 /*
31804 ** Lock the file with the lock specified by parameter eFileLock - one
31805 ** of the following:
31806 **
31807 ** (1) SHARED_LOCK
31808 ** (2) RESERVED_LOCK
31809 ** (3) PENDING_LOCK
31810 ** (4) EXCLUSIVE_LOCK
31811 **
31812 ** Sometimes when requesting one lock state, additional lock states
31813 ** are inserted in between. The locking might fail on one of the later
31814 ** transitions leaving the lock state different from what it started but
31815 ** still short of its goal. The following chart shows the allowed
31816 ** transitions and the inserted intermediate states:
31817 **
31818 ** UNLOCKED -> SHARED
31819 ** SHARED -> RESERVED
31820 ** SHARED -> (PENDING) -> EXCLUSIVE
31821 ** RESERVED -> (PENDING) -> EXCLUSIVE
31822 ** PENDING -> EXCLUSIVE
31823 **
31824 ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
31825 ** lock states in the sqlite3_file structure, but all locks SHARED or
31826 ** above are really EXCLUSIVE locks and exclude all other processes from
31827 ** access the file.
31828 **
31829 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
31830 ** routine to lower a locking level.
31831 */
31832 static int semXLock(sqlite3_file *id, int eFileLock) {
31833  unixFile *pFile = (unixFile*)id;
31834  sem_t *pSem = pFile->pInode->pSem;
31835  int rc = SQLITE_OK;
31836 
31837  /* if we already have a lock, it is exclusive.
31838  ** Just adjust level and punt on outta here. */
31839  if (pFile->eFileLock > NO_LOCK) {
31840  pFile->eFileLock = eFileLock;
31841  rc = SQLITE_OK;
31842  goto sem_end_lock;
31843  }
31844 
31845  /* lock semaphore now but bail out when already locked. */
31846  if( sem_trywait(pSem)==-1 ){
31847  rc = SQLITE_BUSY;
31848  goto sem_end_lock;
31849  }
31850 
31851  /* got it, set the type and return ok */
31852  pFile->eFileLock = eFileLock;
31853 
31854  sem_end_lock:
31855  return rc;
31856 }
31857 
31858 /*
31859 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
31860 ** must be either NO_LOCK or SHARED_LOCK.
31861 **
31862 ** If the locking level of the file descriptor is already at or below
31863 ** the requested locking level, this routine is a no-op.
31864 */
31865 static int semXUnlock(sqlite3_file *id, int eFileLock) {
31866  unixFile *pFile = (unixFile*)id;
31867  sem_t *pSem = pFile->pInode->pSem;
31868 
31869  assert( pFile );
31870  assert( pSem );
31871  OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
31872  pFile->eFileLock, osGetpid(0)));
31873  assert( eFileLock<=SHARED_LOCK );
31874 
31875  /* no-op if possible */
31876  if( pFile->eFileLock==eFileLock ){
31877  return SQLITE_OK;
31878  }
31879 
31880  /* shared can just be set because we always have an exclusive */
31881  if (eFileLock==SHARED_LOCK) {
31882  pFile->eFileLock = eFileLock;
31883  return SQLITE_OK;
31884  }
31885 
31886  /* no, really unlock. */
31887  if ( sem_post(pSem)==-1 ) {
31888  int rc, tErrno = errno;
31889  rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
31890  if( IS_LOCK_ERROR(rc) ){
31891  storeLastErrno(pFile, tErrno);
31892  }
31893  return rc;
31894  }
31895  pFile->eFileLock = NO_LOCK;
31896  return SQLITE_OK;
31897 }
31898 
31899 /*
31900  ** Close a file.
31901  */
31902 static int semXClose(sqlite3_file *id) {
31903  if( id ){
31904  unixFile *pFile = (unixFile*)id;
31905  semXUnlock(id, NO_LOCK);
31906  assert( pFile );
31907  unixEnterMutex();
31908  releaseInodeInfo(pFile);
31909  unixLeaveMutex();
31910  closeUnixFile(id);
31911  }
31912  return SQLITE_OK;
31913 }
31914 
31915 #endif /* OS_VXWORKS */
31916 /*
31917 ** Named semaphore locking is only available on VxWorks.
31918 **
31919 *************** End of the named semaphore lock implementation ****************
31920 ******************************************************************************/
31921 
31922 
31923 /******************************************************************************
31924 *************************** Begin AFP Locking *********************************
31925 **
31926 ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
31927 ** on Apple Macintosh computers - both OS9 and OSX.
31928 **
31929 ** Third-party implementations of AFP are available. But this code here
31930 ** only works on OSX.
31931 */
31932 
31933 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31934 /*
31935 ** The afpLockingContext structure contains all afp lock specific state
31936 */
31937 typedef struct afpLockingContext afpLockingContext;
31938 struct afpLockingContext {
31939  int reserved;
31940  const char *dbPath; /* Name of the open file */
31941 };
31942 
31943 struct ByteRangeLockPB2
31944 {
31945  unsigned long long offset; /* offset to first byte to lock */
31946  unsigned long long length; /* nbr of bytes to lock */
31947  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
31948  unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
31949  unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
31950  int fd; /* file desc to assoc this lock with */
31951 };
31952 
31953 #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
31954 
31955 /*
31956 ** This is a utility for setting or clearing a bit-range lock on an
31957 ** AFP filesystem.
31958 **
31959 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
31960 */
31961 static int afpSetLock(
31962  const char *path, /* Name of the file to be locked or unlocked */
31963  unixFile *pFile, /* Open file descriptor on path */
31964  unsigned long long offset, /* First byte to be locked */
31965  unsigned long long length, /* Number of bytes to lock */
31966  int setLockFlag /* True to set lock. False to clear lock */
31967 ){
31968  struct ByteRangeLockPB2 pb;
31969  int err;
31970 
31971  pb.unLockFlag = setLockFlag ? 0 : 1;
31972  pb.startEndFlag = 0;
31973  pb.offset = offset;
31974  pb.length = length;
31975  pb.fd = pFile->h;
31976 
31977  OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
31978  (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
31979  offset, length));
31980  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
31981  if ( err==-1 ) {
31982  int rc;
31983  int tErrno = errno;
31984  OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
31985  path, tErrno, strerror(tErrno)));
31986 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
31987  rc = SQLITE_BUSY;
31988 #else
31989  rc = sqliteErrorFromPosixError(tErrno,
31990  setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
31991 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
31992  if( IS_LOCK_ERROR(rc) ){
31993  storeLastErrno(pFile, tErrno);
31994  }
31995  return rc;
31996  } else {
31997  return SQLITE_OK;
31998  }
31999 }
32000 
32001 /*
32002 ** This routine checks if there is a RESERVED lock held on the specified
32003 ** file by this or any other process. If such a lock is held, set *pResOut
32004 ** to a non-zero value otherwise *pResOut is set to zero. The return value
32005 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
32006 */
32007 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
32008  int rc = SQLITE_OK;
32009  int reserved = 0;
32010  unixFile *pFile = (unixFile*)id;
32011  afpLockingContext *context;
32012 
32013  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
32014 
32015  assert( pFile );
32016  context = (afpLockingContext *) pFile->lockingContext;
32017  if( context->reserved ){
32018  *pResOut = 1;
32019  return SQLITE_OK;
32020  }
32021  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
32022 
32023  /* Check if a thread in this process holds such a lock */
32024  if( pFile->pInode->eFileLock>SHARED_LOCK ){
32025  reserved = 1;
32026  }
32027 
32028  /* Otherwise see if some other process holds it.
32029  */
32030  if( !reserved ){
32031  /* lock the RESERVED byte */
32032  int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
32033  if( SQLITE_OK==lrc ){
32034  /* if we succeeded in taking the reserved lock, unlock it to restore
32035  ** the original state */
32036  lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
32037  } else {
32038  /* if we failed to get the lock then someone else must have it */
32039  reserved = 1;
32040  }
32041  if( IS_LOCK_ERROR(lrc) ){
32042  rc=lrc;
32043  }
32044  }
32045 
32046  unixLeaveMutex();
32047  OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
32048 
32049  *pResOut = reserved;
32050  return rc;
32051 }
32052 
32053 /*
32054 ** Lock the file with the lock specified by parameter eFileLock - one
32055 ** of the following:
32056 **
32057 ** (1) SHARED_LOCK
32058 ** (2) RESERVED_LOCK
32059 ** (3) PENDING_LOCK
32060 ** (4) EXCLUSIVE_LOCK
32061 **
32062 ** Sometimes when requesting one lock state, additional lock states
32063 ** are inserted in between. The locking might fail on one of the later
32064 ** transitions leaving the lock state different from what it started but
32065 ** still short of its goal. The following chart shows the allowed
32066 ** transitions and the inserted intermediate states:
32067 **
32068 ** UNLOCKED -> SHARED
32069 ** SHARED -> RESERVED
32070 ** SHARED -> (PENDING) -> EXCLUSIVE
32071 ** RESERVED -> (PENDING) -> EXCLUSIVE
32072 ** PENDING -> EXCLUSIVE
32073 **
32074 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
32075 ** routine to lower a locking level.
32076 */
32077 static int afpLock(sqlite3_file *id, int eFileLock){
32078  int rc = SQLITE_OK;
32079  unixFile *pFile = (unixFile*)id;
32080  unixInodeInfo *pInode = pFile->pInode;
32081  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
32082 
32083  assert( pFile );
32084  OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
32085  azFileLock(eFileLock), azFileLock(pFile->eFileLock),
32086  azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
32087 
32088  /* If there is already a lock of this type or more restrictive on the
32089  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
32090  ** unixEnterMutex() hasn't been called yet.
32091  */
32092  if( pFile->eFileLock>=eFileLock ){
32093  OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
32094  azFileLock(eFileLock)));
32095  return SQLITE_OK;
32096  }
32097 
32098  /* Make sure the locking sequence is correct
32099  ** (1) We never move from unlocked to anything higher than shared lock.
32100  ** (2) SQLite never explicitly requests a pendig lock.
32101  ** (3) A shared lock is always held when a reserve lock is requested.
32102  */
32103  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
32104  assert( eFileLock!=PENDING_LOCK );
32105  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
32106 
32107  /* This mutex is needed because pFile->pInode is shared across threads
32108  */
32109  unixEnterMutex();
32110  pInode = pFile->pInode;
32111 
32112  /* If some thread using this PID has a lock via a different unixFile*
32113  ** handle that precludes the requested lock, return BUSY.
32114  */
32115  if( (pFile->eFileLock!=pInode->eFileLock &&
32116  (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
32117  ){
32118  rc = SQLITE_BUSY;
32119  goto afp_end_lock;
32120  }
32121 
32122  /* If a SHARED lock is requested, and some thread using this PID already
32123  ** has a SHARED or RESERVED lock, then increment reference counts and
32124  ** return SQLITE_OK.
32125  */
32126  if( eFileLock==SHARED_LOCK &&
32127  (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
32128  assert( eFileLock==SHARED_LOCK );
32129  assert( pFile->eFileLock==0 );
32130  assert( pInode->nShared>0 );
32131  pFile->eFileLock = SHARED_LOCK;
32132  pInode->nShared++;
32133  pInode->nLock++;
32134  goto afp_end_lock;
32135  }
32136 
32137  /* A PENDING lock is needed before acquiring a SHARED lock and before
32138  ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
32139  ** be released.
32140  */
32141  if( eFileLock==SHARED_LOCK
32142  || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
32143  ){
32144  int failed;
32145  failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
32146  if (failed) {
32147  rc = failed;
32148  goto afp_end_lock;
32149  }
32150  }
32151 
32152  /* If control gets to this point, then actually go ahead and make
32153  ** operating system calls for the specified lock.
32154  */
32155  if( eFileLock==SHARED_LOCK ){
32156  int lrc1, lrc2, lrc1Errno = 0;
32157  long lk, mask;
32158 
32159  assert( pInode->nShared==0 );
32160  assert( pInode->eFileLock==0 );
32161 
32162  mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
32163  /* Now get the read-lock SHARED_LOCK */
32164  /* note that the quality of the randomness doesn't matter that much */
32165  lk = random();
32166  pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
32167  lrc1 = afpSetLock(context->dbPath, pFile,
32168  SHARED_FIRST+pInode->sharedByte, 1, 1);
32169  if( IS_LOCK_ERROR(lrc1) ){
32170  lrc1Errno = pFile->lastErrno;
32171  }
32172  /* Drop the temporary PENDING lock */
32173  lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
32174 
32175  if( IS_LOCK_ERROR(lrc1) ) {
32176  storeLastErrno(pFile, lrc1Errno);
32177  rc = lrc1;
32178  goto afp_end_lock;
32179  } else if( IS_LOCK_ERROR(lrc2) ){
32180  rc = lrc2;
32181  goto afp_end_lock;
32182  } else if( lrc1 != SQLITE_OK ) {
32183  rc = lrc1;
32184  } else {
32185  pFile->eFileLock = SHARED_LOCK;
32186  pInode->nLock++;
32187  pInode->nShared = 1;
32188  }
32189  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
32190  /* We are trying for an exclusive lock but another thread in this
32191  ** same process is still holding a shared lock. */
32192  rc = SQLITE_BUSY;
32193  }else{
32194  /* The request was for a RESERVED or EXCLUSIVE lock. It is
32195  ** assumed that there is a SHARED or greater lock on the file
32196  ** already.
32197  */
32198  int failed = 0;
32199  assert( 0!=pFile->eFileLock );
32200  if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
32201  /* Acquire a RESERVED lock */
32202  failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
32203  if( !failed ){
32204  context->reserved = 1;
32205  }
32206  }
32207  if (!failed && eFileLock == EXCLUSIVE_LOCK) {
32208  /* Acquire an EXCLUSIVE lock */
32209 
32210  /* Remove the shared lock before trying the range. we'll need to
32211  ** reestablish the shared lock if we can't get the afpUnlock
32212  */
32213  if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
32214  pInode->sharedByte, 1, 0)) ){
32215  int failed2 = SQLITE_OK;
32216  /* now attemmpt to get the exclusive lock range */
32217  failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
32218  SHARED_SIZE, 1);
32219  if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
32220  SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
32221  /* Can't reestablish the shared lock. Sqlite can't deal, this is
32222  ** a critical I/O error
32223  */
32224  rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
32225  SQLITE_IOERR_LOCK;
32226  goto afp_end_lock;
32227  }
32228  }else{
32229  rc = failed;
32230  }
32231  }
32232  if( failed ){
32233  rc = failed;
32234  }
32235  }
32236 
32237  if( rc==SQLITE_OK ){
32238  pFile->eFileLock = eFileLock;
32239  pInode->eFileLock = eFileLock;
32240  }else if( eFileLock==EXCLUSIVE_LOCK ){
32241  pFile->eFileLock = PENDING_LOCK;
32242  pInode->eFileLock = PENDING_LOCK;
32243  }
32244 
32245 afp_end_lock:
32246  unixLeaveMutex();
32247  OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
32248  rc==SQLITE_OK ? "ok" : "failed"));
32249  return rc;
32250 }
32251 
32252 /*
32253 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
32254 ** must be either NO_LOCK or SHARED_LOCK.
32255 **
32256 ** If the locking level of the file descriptor is already at or below
32257 ** the requested locking level, this routine is a no-op.
32258 */
32259 static int afpUnlock(sqlite3_file *id, int eFileLock) {
32260  int rc = SQLITE_OK;
32261  unixFile *pFile = (unixFile*)id;
32262  unixInodeInfo *pInode;
32263  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
32264  int skipShared = 0;
32265 #ifdef SQLITE_TEST
32266  int h = pFile->h;
32267 #endif
32268 
32269  assert( pFile );
32270  OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
32271  pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
32272  osGetpid(0)));
32273 
32274  assert( eFileLock<=SHARED_LOCK );
32275  if( pFile->eFileLock<=eFileLock ){
32276  return SQLITE_OK;
32277  }
32278  unixEnterMutex();
32279  pInode = pFile->pInode;
32280  assert( pInode->nShared!=0 );
32281  if( pFile->eFileLock>SHARED_LOCK ){
32282  assert( pInode->eFileLock==pFile->eFileLock );
32283  SimulateIOErrorBenign(1);
32284  SimulateIOError( h=(-1) )
32285  SimulateIOErrorBenign(0);
32286 
32287 #ifdef SQLITE_DEBUG
32288  /* When reducing a lock such that other processes can start
32289  ** reading the database file again, make sure that the
32290  ** transaction counter was updated if any part of the database
32291  ** file changed. If the transaction counter is not updated,
32292  ** other connections to the same file might not realize that
32293  ** the file has changed and hence might not know to flush their
32294  ** cache. The use of a stale cache can lead to database corruption.
32295  */
32296  assert( pFile->inNormalWrite==0
32297  || pFile->dbUpdate==0
32298  || pFile->transCntrChng==1 );
32299  pFile->inNormalWrite = 0;
32300 #endif
32301 
32302  if( pFile->eFileLock==EXCLUSIVE_LOCK ){
32303  rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
32304  if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
32305  /* only re-establish the shared lock if necessary */
32306  int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
32307  rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
32308  } else {
32309  skipShared = 1;
32310  }
32311  }
32312  if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
32313  rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
32314  }
32315  if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
32316  rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
32317  if( !rc ){
32318  context->reserved = 0;
32319  }
32320  }
32321  if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
32322  pInode->eFileLock = SHARED_LOCK;
32323  }
32324  }
32325  if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
32326 
32327  /* Decrement the shared lock counter. Release the lock using an
32328  ** OS call only when all threads in this same process have released
32329  ** the lock.
32330  */
32331  unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
32332  pInode->nShared--;
32333  if( pInode->nShared==0 ){
32334  SimulateIOErrorBenign(1);
32335  SimulateIOError( h=(-1) )
32336  SimulateIOErrorBenign(0);
32337  if( !skipShared ){
32338  rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
32339  }
32340  if( !rc ){
32341  pInode->eFileLock = NO_LOCK;
32342  pFile->eFileLock = NO_LOCK;
32343  }
32344  }
32345  if( rc==SQLITE_OK ){
32346  pInode->nLock--;
32347  assert( pInode->nLock>=0 );
32348  if( pInode->nLock==0 ){
32349  closePendingFds(pFile);
32350  }
32351  }
32352  }
32353 
32354  unixLeaveMutex();
32355  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
32356  return rc;
32357 }
32358 
32359 /*
32360 ** Close a file & cleanup AFP specific locking context
32361 */
32362 static int afpClose(sqlite3_file *id) {
32363  int rc = SQLITE_OK;
32364  unixFile *pFile = (unixFile*)id;
32365  assert( id!=0 );
32366  afpUnlock(id, NO_LOCK);
32367  unixEnterMutex();
32368  if( pFile->pInode && pFile->pInode->nLock ){
32369  /* If there are outstanding locks, do not actually close the file just
32370  ** yet because that would clear those locks. Instead, add the file
32371  ** descriptor to pInode->aPending. It will be automatically closed when
32372  ** the last lock is cleared.
32373  */
32374  setPendingFd(pFile);
32375  }
32376  releaseInodeInfo(pFile);
32377  sqlite3_free(pFile->lockingContext);
32378  rc = closeUnixFile(id);
32379  unixLeaveMutex();
32380  return rc;
32381 }
32382 
32383 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
32384 /*
32385 ** The code above is the AFP lock implementation. The code is specific
32386 ** to MacOSX and does not work on other unix platforms. No alternative
32387 ** is available. If you don't compile for a mac, then the "unix-afp"
32388 ** VFS is not available.
32389 **
32390 ********************* End of the AFP lock implementation **********************
32391 ******************************************************************************/
32392 
32393 /******************************************************************************
32394 *************************** Begin NFS Locking ********************************/
32395 
32396 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
32397 /*
32398  ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
32399  ** must be either NO_LOCK or SHARED_LOCK.
32400  **
32401  ** If the locking level of the file descriptor is already at or below
32402  ** the requested locking level, this routine is a no-op.
32403  */
32404 static int nfsUnlock(sqlite3_file *id, int eFileLock){
32405  return posixUnlock(id, eFileLock, 1);
32406 }
32407 
32408 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
32409 /*
32410 ** The code above is the NFS lock implementation. The code is specific
32411 ** to MacOSX and does not work on other unix platforms. No alternative
32412 ** is available.
32413 **
32414 ********************* End of the NFS lock implementation **********************
32415 ******************************************************************************/
32416 
32417 /******************************************************************************
32418 **************** Non-locking sqlite3_file methods *****************************
32419 **
32420 ** The next division contains implementations for all methods of the
32421 ** sqlite3_file object other than the locking methods. The locking
32422 ** methods were defined in divisions above (one locking method per
32423 ** division). Those methods that are common to all locking modes
32424 ** are gather together into this division.
32425 */
32426 
32427 /*
32428 ** Seek to the offset passed as the second argument, then read cnt
32429 ** bytes into pBuf. Return the number of bytes actually read.
32430 **
32431 ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
32432 ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
32433 ** one system to another. Since SQLite does not define USE_PREAD
32434 ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
32435 ** See tickets #2741 and #2681.
32436 **
32437 ** To avoid stomping the errno value on a failed read the lastErrno value
32438 ** is set before returning.
32439 */
32440 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
32441  int got;
32442  int prior = 0;
32443 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
32444  i64 newOffset;
32445 #endif
32446  TIMER_START;
32447  assert( cnt==(cnt&0x1ffff) );
32448  assert( id->h>2 );
32449  do{
32450 #if defined(USE_PREAD)
32451  got = osPread(id->h, pBuf, cnt, offset);
32452  SimulateIOError( got = -1 );
32453 #elif defined(USE_PREAD64)
32454  got = osPread64(id->h, pBuf, cnt, offset);
32455  SimulateIOError( got = -1 );
32456 #else
32457  newOffset = lseek(id->h, offset, SEEK_SET);
32458  SimulateIOError( newOffset = -1 );
32459  if( newOffset<0 ){
32460  storeLastErrno((unixFile*)id, errno);
32461  return -1;
32462  }
32463  got = osRead(id->h, pBuf, cnt);
32464 #endif
32465  if( got==cnt ) break;
32466  if( got<0 ){
32467  if( errno==EINTR ){ got = 1; continue; }
32468  prior = 0;
32469  storeLastErrno((unixFile*)id, errno);
32470  break;
32471  }else if( got>0 ){
32472  cnt -= got;
32473  offset += got;
32474  prior += got;
32475  pBuf = (void*)(got + (char*)pBuf);
32476  }
32477  }while( got>0 );
32478  TIMER_END;
32479  OSTRACE(("READ %-3d %5d %7lld %llu\n",
32480  id->h, got+prior, offset-prior, TIMER_ELAPSED));
32481  return got+prior;
32482 }
32483 
32484 /*
32485 ** Read data from a file into a buffer. Return SQLITE_OK if all
32486 ** bytes were read successfully and SQLITE_IOERR if anything goes
32487 ** wrong.
32488 */
32489 static int unixRead(
32490  sqlite3_file *id,
32491  void *pBuf,
32492  int amt,
32493  sqlite3_int64 offset
32494 ){
32495  unixFile *pFile = (unixFile *)id;
32496  int got;
32497  assert( id );
32498  assert( offset>=0 );
32499  assert( amt>0 );
32500 
32501  /* If this is a database file (not a journal, master-journal or temp
32502  ** file), the bytes in the locking range should never be read or written. */
32503 #if 0
32504  assert( pFile->pUnused==0
32505  || offset>=PENDING_BYTE+512
32506  || offset+amt<=PENDING_BYTE
32507  );
32508 #endif
32509 
32510 #if SQLITE_MAX_MMAP_SIZE>0
32511  /* Deal with as much of this read request as possible by transfering
32512  ** data from the memory mapping using memcpy(). */
32513  if( offset<pFile->mmapSize ){
32514  if( offset+amt <= pFile->mmapSize ){
32515  memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
32516  return SQLITE_OK;
32517  }else{
32518  int nCopy = pFile->mmapSize - offset;
32519  memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
32520  pBuf = &((u8 *)pBuf)[nCopy];
32521  amt -= nCopy;
32522  offset += nCopy;
32523  }
32524  }
32525 #endif
32526 
32527  got = seekAndRead(pFile, offset, pBuf, amt);
32528  if( got==amt ){
32529  return SQLITE_OK;
32530  }else if( got<0 ){
32531  /* lastErrno set by seekAndRead */
32532  return SQLITE_IOERR_READ;
32533  }else{
32534  storeLastErrno(pFile, 0); /* not a system error */
32535  /* Unread parts of the buffer must be zero-filled */
32536  memset(&((char*)pBuf)[got], 0, amt-got);
32537  return SQLITE_IOERR_SHORT_READ;
32538  }
32539 }
32540 
32541 /*
32542 ** Attempt to seek the file-descriptor passed as the first argument to
32543 ** absolute offset iOff, then attempt to write nBuf bytes of data from
32544 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
32545 ** return the actual number of bytes written (which may be less than
32546 ** nBuf).
32547 */
32548 static int seekAndWriteFd(
32549  int fd, /* File descriptor to write to */
32550  i64 iOff, /* File offset to begin writing at */
32551  const void *pBuf, /* Copy data from this buffer to the file */
32552  int nBuf, /* Size of buffer pBuf in bytes */
32553  int *piErrno /* OUT: Error number if error occurs */
32554 ){
32555  int rc = 0; /* Value returned by system call */
32556 
32557  assert( nBuf==(nBuf&0x1ffff) );
32558  assert( fd>2 );
32559  assert( piErrno!=0 );
32560  nBuf &= 0x1ffff;
32561  TIMER_START;
32562 
32563 #if defined(USE_PREAD)
32564  do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
32565 #elif defined(USE_PREAD64)
32566  do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
32567 #else
32568  do{
32569  i64 iSeek = lseek(fd, iOff, SEEK_SET);
32570  SimulateIOError( iSeek = -1 );
32571  if( iSeek<0 ){
32572  rc = -1;
32573  break;
32574  }
32575  rc = osWrite(fd, pBuf, nBuf);
32576  }while( rc<0 && errno==EINTR );
32577 #endif
32578 
32579  TIMER_END;
32580  OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
32581 
32582  if( rc<0 ) *piErrno = errno;
32583  return rc;
32584 }
32585 
32586 
32587 /*
32588 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
32589 ** Return the number of bytes actually read. Update the offset.
32590 **
32591 ** To avoid stomping the errno value on a failed write the lastErrno value
32592 ** is set before returning.
32593 */
32594 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
32595  return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
32596 }
32597 
32598 
32599 /*
32600 ** Write data from a buffer into a file. Return SQLITE_OK on success
32601 ** or some other error code on failure.
32602 */
32603 static int unixWrite(
32604  sqlite3_file *id,
32605  const void *pBuf,
32606  int amt,
32607  sqlite3_int64 offset
32608 ){
32609  unixFile *pFile = (unixFile*)id;
32610  int wrote = 0;
32611  assert( id );
32612  assert( amt>0 );
32613 
32614  /* If this is a database file (not a journal, master-journal or temp
32615  ** file), the bytes in the locking range should never be read or written. */
32616 #if 0
32617  assert( pFile->pUnused==0
32618  || offset>=PENDING_BYTE+512
32619  || offset+amt<=PENDING_BYTE
32620  );
32621 #endif
32622 
32623 #ifdef SQLITE_DEBUG
32624  /* If we are doing a normal write to a database file (as opposed to
32625  ** doing a hot-journal rollback or a write to some file other than a
32626  ** normal database file) then record the fact that the database
32627  ** has changed. If the transaction counter is modified, record that
32628  ** fact too.
32629  */
32630  if( pFile->inNormalWrite ){
32631  pFile->dbUpdate = 1; /* The database has been modified */
32632  if( offset<=24 && offset+amt>=27 ){
32633  int rc;
32634  char oldCntr[4];
32635  SimulateIOErrorBenign(1);
32636  rc = seekAndRead(pFile, 24, oldCntr, 4);
32637  SimulateIOErrorBenign(0);
32638  if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
32639  pFile->transCntrChng = 1; /* The transaction counter has changed */
32640  }
32641  }
32642  }
32643 #endif
32644 
32645 #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
32646  /* Deal with as much of this write request as possible by transfering
32647  ** data from the memory mapping using memcpy(). */
32648  if( offset<pFile->mmapSize ){
32649  if( offset+amt <= pFile->mmapSize ){
32650  memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
32651  return SQLITE_OK;
32652  }else{
32653  int nCopy = pFile->mmapSize - offset;
32654  memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
32655  pBuf = &((u8 *)pBuf)[nCopy];
32656  amt -= nCopy;
32657  offset += nCopy;
32658  }
32659  }
32660 #endif
32661 
32662  while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
32663  amt -= wrote;
32664  offset += wrote;
32665  pBuf = &((char*)pBuf)[wrote];
32666  }
32667  SimulateIOError(( wrote=(-1), amt=1 ));
32668  SimulateDiskfullError(( wrote=0, amt=1 ));
32669 
32670  if( amt>wrote ){
32671  if( wrote<0 && pFile->lastErrno!=ENOSPC ){
32672  /* lastErrno set by seekAndWrite */
32673  return SQLITE_IOERR_WRITE;
32674  }else{
32675  storeLastErrno(pFile, 0); /* not a system error */
32676  return SQLITE_FULL;
32677  }
32678  }
32679 
32680  return SQLITE_OK;
32681 }
32682 
32683 #ifdef SQLITE_TEST
32684 /*
32685 ** Count the number of fullsyncs and normal syncs. This is used to test
32686 ** that syncs and fullsyncs are occurring at the right times.
32687 */
32688 SQLITE_API int sqlite3_sync_count = 0;
32689 SQLITE_API int sqlite3_fullsync_count = 0;
32690 #endif
32691 
32692 /*
32693 ** We do not trust systems to provide a working fdatasync(). Some do.
32694 ** Others do no. To be safe, we will stick with the (slightly slower)
32695 ** fsync(). If you know that your system does support fdatasync() correctly,
32696 ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
32697 */
32698 #if !defined(fdatasync) && !HAVE_FDATASYNC
32699 # define fdatasync fsync
32700 #endif
32701 
32702 /*
32703 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
32704 ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
32705 ** only available on Mac OS X. But that could change.
32706 */
32707 #ifdef F_FULLFSYNC
32708 # define HAVE_FULLFSYNC 1
32709 #else
32710 # define HAVE_FULLFSYNC 0
32711 #endif
32712 
32713 
32714 /*
32715 ** The fsync() system call does not work as advertised on many
32716 ** unix systems. The following procedure is an attempt to make
32717 ** it work better.
32718 **
32719 ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
32720 ** for testing when we want to run through the test suite quickly.
32721 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
32722 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
32723 ** or power failure will likely corrupt the database file.
32724 **
32725 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
32726 ** The idea behind dataOnly is that it should only write the file content
32727 ** to disk, not the inode. We only set dataOnly if the file size is
32728 ** unchanged since the file size is part of the inode. However,
32729 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
32730 ** file size has changed. The only real difference between fdatasync()
32731 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
32732 ** inode if the mtime or owner or other inode attributes have changed.
32733 ** We only care about the file size, not the other file attributes, so
32734 ** as far as SQLite is concerned, an fdatasync() is always adequate.
32735 ** So, we always use fdatasync() if it is available, regardless of
32736 ** the value of the dataOnly flag.
32737 */
32738 static int full_fsync(int fd, int fullSync, int dataOnly){
32739  int rc;
32740 
32741  /* The following "ifdef/elif/else/" block has the same structure as
32742  ** the one below. It is replicated here solely to avoid cluttering
32743  ** up the real code with the UNUSED_PARAMETER() macros.
32744  */
32745 #ifdef SQLITE_NO_SYNC
32746  UNUSED_PARAMETER(fd);
32747  UNUSED_PARAMETER(fullSync);
32748  UNUSED_PARAMETER(dataOnly);
32749 #elif HAVE_FULLFSYNC
32750  UNUSED_PARAMETER(dataOnly);
32751 #else
32752  UNUSED_PARAMETER(fullSync);
32753  UNUSED_PARAMETER(dataOnly);
32754 #endif
32755 
32756  /* Record the number of times that we do a normal fsync() and
32757  ** FULLSYNC. This is used during testing to verify that this procedure
32758  ** gets called with the correct arguments.
32759  */
32760 #ifdef SQLITE_TEST
32761  if( fullSync ) sqlite3_fullsync_count++;
32762  sqlite3_sync_count++;
32763 #endif
32764 
32765  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
32766  ** no-op. But go ahead and call fstat() to validate the file
32767  ** descriptor as we need a method to provoke a failure during
32768  ** coverate testing.
32769  */
32770 #ifdef SQLITE_NO_SYNC
32771  {
32772  struct stat buf;
32773  rc = osFstat(fd, &buf);
32774  }
32775 #elif HAVE_FULLFSYNC
32776  if( fullSync ){
32777  rc = osFcntl(fd, F_FULLFSYNC, 0);
32778  }else{
32779  rc = 1;
32780  }
32781  /* If the FULLFSYNC failed, fall back to attempting an fsync().
32782  ** It shouldn't be possible for fullfsync to fail on the local
32783  ** file system (on OSX), so failure indicates that FULLFSYNC
32784  ** isn't supported for this file system. So, attempt an fsync
32785  ** and (for now) ignore the overhead of a superfluous fcntl call.
32786  ** It'd be better to detect fullfsync support once and avoid
32787  ** the fcntl call every time sync is called.
32788  */
32789  if( rc ) rc = fsync(fd);
32790 
32791 #elif defined(__APPLE__)
32792  /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
32793  ** so currently we default to the macro that redefines fdatasync to fsync
32794  */
32795  rc = fsync(fd);
32796 #else
32797  rc = fdatasync(fd);
32798 #if OS_VXWORKS
32799  if( rc==-1 && errno==ENOTSUP ){
32800  rc = fsync(fd);
32801  }
32802 #endif /* OS_VXWORKS */
32803 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
32804 
32805  if( OS_VXWORKS && rc!= -1 ){
32806  rc = 0;
32807  }
32808  return rc;
32809 }
32810 
32811 /*
32812 ** Open a file descriptor to the directory containing file zFilename.
32813 ** If successful, *pFd is set to the opened file descriptor and
32814 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
32815 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
32816 ** value.
32817 **
32818 ** The directory file descriptor is used for only one thing - to
32819 ** fsync() a directory to make sure file creation and deletion events
32820 ** are flushed to disk. Such fsyncs are not needed on newer
32821 ** journaling filesystems, but are required on older filesystems.
32822 **
32823 ** This routine can be overridden using the xSetSysCall interface.
32824 ** The ability to override this routine was added in support of the
32825 ** chromium sandbox. Opening a directory is a security risk (we are
32826 ** told) so making it overrideable allows the chromium sandbox to
32827 ** replace this routine with a harmless no-op. To make this routine
32828 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
32829 ** *pFd set to a negative number.
32830 **
32831 ** If SQLITE_OK is returned, the caller is responsible for closing
32832 ** the file descriptor *pFd using close().
32833 */
32834 static int openDirectory(const char *zFilename, int *pFd){
32835  int ii;
32836  int fd = -1;
32837  char zDirname[MAX_PATHNAME+1];
32838 
32839  sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
32840  for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
32841  if( ii>0 ){
32842  zDirname[ii] = '\0';
32843  }else{
32844  if( zDirname[0]!='/' ) zDirname[0] = '.';
32845  zDirname[1] = 0;
32846  }
32847  fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
32848  if( fd>=0 ){
32849  OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
32850  }
32851  *pFd = fd;
32852  if( fd>=0 ) return SQLITE_OK;
32853  return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
32854 }
32855 
32856 /*
32857 ** Make sure all writes to a particular file are committed to disk.
32858 **
32859 ** If dataOnly==0 then both the file itself and its metadata (file
32860 ** size, access time, etc) are synced. If dataOnly!=0 then only the
32861 ** file data is synced.
32862 **
32863 ** Under Unix, also make sure that the directory entry for the file
32864 ** has been created by fsync-ing the directory that contains the file.
32865 ** If we do not do this and we encounter a power failure, the directory
32866 ** entry for the journal might not exist after we reboot. The next
32867 ** SQLite to access the file will not know that the journal exists (because
32868 ** the directory entry for the journal was never created) and the transaction
32869 ** will not roll back - possibly leading to database corruption.
32870 */
32871 static int unixSync(sqlite3_file *id, int flags){
32872  int rc;
32873  unixFile *pFile = (unixFile*)id;
32874 
32875  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
32876  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
32877 
32878  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
32879  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
32880  || (flags&0x0F)==SQLITE_SYNC_FULL